Skip to content

Instantly share code, notes, and snippets.

@4poc
Created July 21, 2012 13:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save 4poc/3155832 to your computer and use it in GitHub Desktop.
Save 4poc/3155832 to your computer and use it in GitHub Desktop.
C++11 Callbacks with function and lambda
#include <iostream>
#include <vector>
#include <functional>
class WorkingClass {
public:
typedef const std::function<void (int)> handler_t;
void AddHandler(handler_t& h) {
handlerList.push_back(&h);
}
void DoStuff() {
for (auto& handler : handlerList) {
(*handler)(42);
(*handler)(23);
}
}
private:
std::vector<handler_t*> handlerList;
};
int main() {
WorkingClass wc;
wc.AddHandler([&](int num) {
std::cout << "A: " << num << std::endl;
});
wc.AddHandler([&](int num) {
std::cout << "B: " << num << std::endl;
});
wc.DoStuff();
}
@amzhang
Copy link

amzhang commented Jun 25, 2019

Why store "handler_t*" instead of "handler_t"?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment