1. 程式人生 > >用函式指標簡化if/else switch/case

用函式指標簡化if/else switch/case

開發中常遇到一族同類型函式的處理呼叫情況,開始時候簡單情況就使用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;
}