Simplify if/else switch/case with function pointers

In development, we often encounter the processing and calling of a family of functions of the same type. In the beginning, if / else is used for simple cases. When there are more and more branches, the code looks long and difficult to maintain. In this case, you can consider using functions. Pointer mapping to simplify code.


#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;
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325507980&siteId=291194637