| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- #include <stdlib.h>
- #include <stdio.h>
- #include <functional>
- #include <vector>
- using namespace std;
- class Caller {
- public:
- uint8_t age = 12;
- template<class T> void addCallback(T* const object, void(T::* const mf)(bool, int))
- {
- using namespace std::placeholders;
- callbacks_.emplace_back(std::bind(mf, object, _1, _2));
- }
- void addCallback(void(* const fun)(bool, int))
- {
- callbacks_.emplace_back(fun);
- }
- void callCallbacks(bool firstval, int secondval)
- {
- auto self = this;
- for (const auto& cb : callbacks_)
- cb(firstval, secondval);
- }
- private:
- std::vector<std::function<void(bool, int)>> callbacks_;
- };
- class Callee {
- public:
- void MyFunction(bool b, int i) {
- printf("MyRegularFunction: %d %d", b, i);
- }
- };
- void MyRegularFunction(bool b, int i) {
- printf("MyRegularFunction: %d %d", b, i);
- }
- Caller caller = Caller();
- Callee callee = Callee();
- //then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`
- int main(int argc, char const* argv[]) {
- printf("\nCompiler:%ld\n", __cplusplus);
- // caller.addCallback(&Callee::MyFunction);
- //or to add a call back to a regular function
- caller.addCallback(&MyRegularFunction);// Main method
- caller.callCallbacks(true, 12);
- return 0;
- }
|