Search code examples
c++callbackfunction-pointersstd-function

callback in C++ struct


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:

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.


Solution

  • If you want to delay the call to T.foo, then you could use a lambda like this:

        T.foo = [this](int x) { return plus(x); };
        T.foo(5);