Last active
September 18, 2018 07:36
-
-
Save pnck/d92e10d778ca285407b068ead990befd to your computer and use it in GitHub Desktop.
使用成员指针和闭包任意连接调用链
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename C, typename... P> | |
void connect(std::function<void()> &trigger, C *instance, | |
void (C::*member_ptr)(P...), P... params) { | |
trigger = [=]() { | |
trigger(); | |
(instance->*member_ptr)(params...); | |
}; | |
} | |
struct A { | |
void foo() { std::cout << "foooo" << std::endl; } | |
}; | |
struct B { | |
void bar(int n) { std::cout << "baaaar" << n << std::endl; } | |
}; | |
void signal1() { std::cout << "signal with side effect" << std::endl; } | |
void signal2() {} | |
int main() { | |
A a; | |
B b; | |
std::map<std::string, std::function<void()>> dispatch_map = { | |
{"sig1", signal1}, {"sig2", signal2}}; | |
std::string input; | |
do { | |
std::getline(std::cin,input); | |
if (input == "connect1a") { | |
connect(dispatch_map["sig1"], &a, &A::foo); | |
} else if (input == "connect2a") { | |
connect(dispatch_map["sig2"], &a, &A::foo); | |
} else if (input == "connect1b") { | |
connect(dispatch_map["sig1"], &b, &B::bar, 1); | |
} else if (input == "connect2b") { | |
connect(dispatch_map["sig2"], &b, &B::bar, 2); | |
} else if (input == "disconnect1") { | |
dispatch_map["sig1"] = signal1; | |
} else if (input == "disconnect2") { | |
dispatch_map["sig2"] = signal2; | |
} | |
if (dispatch_map.find(input) != dispatch_map.end()) { | |
dispatch_map[input](); | |
} | |
} while (!input.empty()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment