mercredi 8 septembre 2021

C++ std::function as callback argument using std::bind [duplicate]

implementing a callback function which needs two int arguments,

but the member function C::handle need no arguments and it still calls well in B::setCallback.

it makes me confuse why it works and where the two int arguments go.

#include <iostream>
#include <functional>

class A
{
public:
    A() {}
    ~A() {}
};

typedef std::function<void(int,int)> Functor;

class B
{
public:
    B() {}
    ~B() {}
    void setCallback(const Functor& cb) {
        std::cout << "B setCallback!" << std::endl;
        cb(1,1);
    };
};

class C
{
public:
    C(B* b) :b_(b) {}
    ~C() {}
    void handle() {
        std::cout << "C handle!" << std::endl;
    };
    B* b_;
};

int main()
{
    A a;
    B b;
    C c(&b);

    auto f = std::bind(&C::handle, &c);
    c.b_->setCallback(f);

    std::cin.get();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire