C++ delegate

Classé dans : C++ | 0

https://blog.actorsfit.com/a?ID=00850-ca43f315-3160-4fca-b10b-5861f8ea566a

3.2 Implementation using lambda expressions

Using lambda expressions can simplify this process. Refer to the following piece of code, classB registers a member function as a callback function to classA, and classA saves this callback function (std::function object) to member variables for later use use,

#include <iostream>
#include <functional>
#include <memory>

class classA
{
typedef std::function<void(int i)> callback_t;

public:
    classA() {}
    ~classA() {}
    
    void handle(int i)
    {
        std::cout << "classA::handle" << std::endl;
        
        cbHandle(i);
    }

    void registCb(callback_t func)
    {cbHandle = std::move(func);}
private:
    callback_t cbHandle;
};

class classB
{
public:
    classB(classA& cA) 
    {       
        cA.registCb([this](int i){classB::handle(i);});
    }
    ~classB() {}
    
    void handle(int i)
    {
        std::cout << "classB, handle message" << i << std::endl;
    }
};

int main()
{
    classA testa;
    classB testb(testa);

    testa.handle(10);
}