| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- #include <iostream>
- #include <functional>
- using std::cout;
- using std::endl;
- class EventHandler
- {
- public:
- /*
- template<typename T>
- void addHandler(T* owner)
- {
- cout << "Handler added..." << endl;
- //Let's pretend an event just occured
- owner->Callback(owner, 1);
- }
- */
- void addHandler(std::function<void(int)> callback)
- {
- cout << "Handler added..." << endl;
- // Let's pretend an event just occured
- callback(1);
- }
- };
- EventHandler* handler;
- /**********************************************************************************************
- *
- */
- class MyClass
- {
- public:
- MyClass() {
- using namespace std::placeholders;
- private_x = 5;
- // handler->addHandler(this);
- handler->addHandler(std::bind(&MyClass::Callback, this, _1));
- }
- void Callback(int x) {
- cout << x + private_x << endl;
- }
-
- int public_x = 12;
- private:
- int private_x;
- };
- /**********************************************************************************************
- *
- */
- class YourClass
- {
- public:
- YourClass()
- {
- using namespace std::placeholders;
- private_y = 8;
- handler->addHandler(std::bind(&YourClass::Callback, this, _1));
- }
- void Callback(int x)
- {
- cout << x + private_y << endl;
- }
- private:
- int private_y;
- };
- /**********************************************************************************************
- *
- */
- void freeStandingCallback(int x)
- {
- cout << x << endl;
- }
- /**********************************************************************************************
- *
- */
- // https://en.cppreference.com/w/cpp/language/function_template
- template<class X>
- void f(X a) {
- printf("Test");
- }
- template<class X>
- void f(X* a) {
- printf("Test");
- }
- void (*p)(int*) = &f;
- // https://en.cppreference.com/w/cpp/language/function_template
- // template<class T1, class T2>
- void g(MyClass* a1, YourClass* a2) {
- printf("access both classes\n");
- printf("MyClass: %d\n", a1->public_x);
- printf("YourClass: private\n");
- }
- int main(int argc, char** argv)
- {
- handler = new EventHandler();
- MyClass* myClass = new MyClass();
- YourClass* yourClass = new YourClass();
- handler->addHandler([](int x) {
- std::cout << "x is " << x << '\n';
- });
- handler->addHandler(freeStandingCallback);
- f(myClass->public_x);
- g(myClass, yourClass);
- }
|