我试图尽可能避免切换,我想出了这个(不是)解决方案。 你知道是否有办法做某事:
enum MyEnum { A, B, C, D, E, F, SIZE=F};
typedef void (*GenericFunction)(int);
template<class EnumType>
struct MyEnumTraits
{
template<EnumType code, Args... args>
void doStuff(args);
};
template<class EnumType, int size, MyEnumTrait>
struct Switcher
{
Switcher()
{
//Do compile time initialization by populating functions_
//doing something like: (pseudo c++ code following)
// template metaprogramming iteration of the EnumType values:
//from the first to the last one (size)
for(int i; i<size;i++)
functions_[i] = (GenericFunction) MyEnumTrait::MyFunctionType; //
}
GenericFunction functions_[size];
};
template<>
struct MyEnumTraits<MyEnum>
{
template<>
void doStuff<A>(int a)
{
// do something
}
};
template<>
struct MyEnumTraits<MyEnum>
{
void doStuff<B,int,int>(int a, int b)
{
// do something else
}
};
template<>
struct MyEnumTraits<MyEnum>
{
template<>
void doStuff<C, std::string>(const std::string& myString)
{
// do something else..
}
};
int main()
{
Switcher<MyEnum, SIZE> switcher;
// Next calls will not work because I need a cast..
//is there any magic I can do to avoid the cast?
// these may work
switcher.functions_[A](3);
switcher.functions_[B](1,2);
switcher.functions_[C]("bla bla");
// this is probably impossible to do... isn't it?
MyEnum en = /* get it from cin */;
switcher.functions_[en](1,2,3);
}
我为糟糕的缩进道歉,我会尝试尽快重构代码
[编辑]更改了代码的最后3行