Skip to content

Instantly share code, notes, and snippets.

@pwrliang
Created May 19, 2018 01:50
Show Gist options
  • Save pwrliang/86803aa5a86dfaf404faeeaaa3d05b63 to your computer and use it in GitHub Desktop.
Save pwrliang/86803aa5a86dfaf404faeeaaa3d05b63 to your computer and use it in GitHub Desktop.
Put class method into map and call it (C++11)
class TestClass {
public:
enum MethodEnum {
METHOD_1,
METHOD_2,
METHOD_3
};
std::map<MethodEnum, std::function<void(void)>> method_map;
void Method1() {
printf("method1\n");
}
void Method2() {
printf("method2\n");
}
void Method3() {
printf("method3\n");
}
void Init() {
method_map.insert(std::make_pair(METHOD_1, std::bind(&TestClass::Method1, this)));
method_map.insert(std::make_pair(METHOD_2, std::bind(&TestClass::Method2, this)));
method_map.insert(std::make_pair(METHOD_3, std::bind(&TestClass::Method3, this)));
}
};
bool Test() {
TestClass test_class;
test_class.Init();
test_class.method_map.at(TestClass::METHOD_1)();
test_class.method_map.at(TestClass::METHOD_2)();
test_class.method_map.at(TestClass::METHOD_3)();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment