Skip to content

Instantly share code, notes, and snippets.

@liaogang
Forked from 4poc/gist:3155832
Created November 8, 2019 12:07
Show Gist options
  • Save liaogang/54060daac610438668b1e8e45116c236 to your computer and use it in GitHub Desktop.
Save liaogang/54060daac610438668b1e8e45116c236 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment