Callback in C++ struct


New Member
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:

    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 = plus(5);    // assign a function (plus or minus);            // 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.


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

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.