c++std-function

How to send the caller object as parameter to the callback function


How can i access a member of a class object from its own callback function? I try to send the caller object as parameter of the callback function and access it from the callback function.

In the following code i get an error: invalid use of void expression on this line test.onEvent(onUpdateEvent(test));

One solution is to define the test object as global and define the onEvent function as void onEvent(const std::function<void()> &callback) and remove parameters from callback functions.

But i would like to know if there is another way. This is an example code:

#include <iostream>

#include <functional>

class Test
{
  public:
    int x;
    void onEvent(const std::function<void(Test)> &callback)
    {
            Test_Callback = callback;
    };

    std::function<void(Test)> Test_Callback;     

    void Update()
    {
        x += 1;
        if (Test_Callback)
        {
            Test_Callback(.......);  <--- What parameter to use? If i use *this, i get the error i mentioned
        }
    }
};

void onUpdateEvent(Test& t)
{
    printf("update %d\r\n", t.x);
}

int main()
{
    Test test;
    test.onEvent(onUpdateEvent(test));

    while (1)
    {
        test.Update();   
    }

    return 0;
}


Solution

  • The problem is that you're using the return value of the function call onUpdateEvent(test) as an argument. This is invalid because onUpdateEvent has void as its return type.


    So to solve this, don't use the return value of the call onUpdateEvent(test) as an argument. Instead just pass a pointer to onUpdateEvent as argument as shown below. Also do note the additional changes made which are highlighted in the comments of the code snippet:

    class Test
    {
      public:
        int x;
        void onEvent(const std::function<void(Test)> &callback)
        {
                Test_Callback = callback;
        };
    
    //---------------------vvvvvvvvvvv------->same type as of onUpdateEvent's parameter
        std::function<void(const Test&)> Test_Callback;     
    
        void Update()
        {
            x += 1;
            if (Test_Callback)
            {
                Test_Callback(*this); // <--- What parameter to use? If i use *this, i get the error i mentioned
            }
        }
    };
    //-----------------vvvvv---------->added const here since this doesn't change anything
    void onUpdateEvent(const Test& t)
    {
        printf("update %d\r\n", t.x);
    }
    
    int main()
    {
        Test test;
        //------------------------v--> pass pointer to function as argument instead of passing return value as arg
        test.onEvent(onUpdateEvent);
    
        while (1)
        {
            test.Update();   
        }
    
        return 0;
    }
    

    Working demo