Created
July 21, 2012 13:30
-
-
Save 4poc/3155832 to your computer and use it in GitHub Desktop.
C++11 Callbacks with function and lambda
This file contains hidden or 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
#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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why store "handler_t*" instead of "handler_t"?