Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a callback function which is non static member function of a class

Tags:

c++

typedef void (*CALLBACK)();
class Filter
{
public:
     void callback()
    {
        cout << "callback" << endl;
    }
};

void SetCallback(CALLBACK pCallBack )
{
    pCallBack();
}



int main()
{
    Filter f;
    SetCallback(f.callback);
}

In main, SetCallback(f.callback); statement is giving error. Can anyone help me to fix the issue

like image 885
user966379 Avatar asked Nov 18 '14 11:11

user966379


1 Answers

A simplier example about callback for 'non-static method' :

#include <iostream>
#include <string>
#include <functional>

using namespace std::placeholders;

class Test
{
public:
    void SetValue(int i) { v = i;}

    int v;
};

int main()
{
    Test a { 123 };

    std::cout << a.v << std::endl;  // print 123

    auto _callback = std::bind(&Test::SetValue, &a, _1); // create the callback

    _callback(55); // call the callback

    std::cout << a.v << std::endl; // print 55

    return 0;
}

output :

123
55
like image 161
user2020 Avatar answered Oct 14 '22 11:10

user2020