开发中常遇到一族同类型函数的处理调用情况,开始时候简单情况就使用if / else 处理,等分支情况越来越多事,代码看起来就很长且不易维护,这种时候可以考虑使用函数指针映射来简化代码。
#include <iostream>
#include <map>
using namespace std;
class A;
typedef void (A::*Call)(string);
enum MyEnum
{
ONE = 1,
TWO,
THREE,
FOUR
};
class A {
public:
explicit A()
{
sCallMap[ONE] = &A::fun1;
sCallMap[TWO] = &A::fun2;
sCallMap[THREE] = &A::fun3;
}
~A(){}
void caller(MyEnum e, string arg)
{
cout << "enum " << e;
if (sCallMap.find(e) == sCallMap.end())
{
cout << " callMap no key " << e;
}
else
{
(this->*sCallMap[e])(arg);
}
}
private:
void fun1(string arg) { cout << arg.c_str(); }
void fun2(string arg) { cout << arg.c_str(); }
void fun3(string arg) { cout << arg.c_str(); }
private:
static map<MyEnum, Call> sCallMap;
};
map<MyEnum, Call> A::sCallMap;
int main(int argc, char *argv[])
{
A a;
a.caller(ONE, " call func1\n");
a.caller(TWO, " call func2\n");
a.caller(THREE, " call func3\n");
a.caller(FOUR, " call func4\n");
getchar();
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/fd32d26152d35a3a1bc62a82e8455353.jpeg)