Callback in C++ struct

Angus

New Member
#1
I have been trying to implement a callback function in c++. Within a class, I have a struct, a number of methods, and a method that creates an instance of the struct with one of the other methods as its argument.

The struct has many other variables, but an illustration is depicted here:
Mã:
class MYCLASS
{
public:
    MYCLASS();

    struct TEST{
        std::function<int(int)> foo;
    };

    int plus(int x){
        return x + 1;
    }

    int minus(int x){
        return x - 1;
    }

    void sim(){
        TEST T;             // make an instance of TEST
        T.foo = plus(5);    // assign TEST.foo a function (plus or minus) 
        T.foo();            // call the method we assigned
    }
};
Within the sim method, I want to create an instance of test and give it either plus or minus, depending on some criterion. Both lines where I try and give the instance T a plus function and subsequently call it are incorrect.
 

Admin

Administrator
Thành viên BQT
#2
If you want to delay the call to T.foo, then you could use a lambda like this:
Mã:
    T.foo = [this](int x) { return plus(x); };
    T.foo(5);
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top