C ++ Function Callbacks: Cannot be converted from member function to function signature

I use a third-party library that allows me to register callbacks for specific events. The register function looks something like this. It uses a callback signature.

typedef int (*Callback)(std::string);

void registerCallback(Callback pCallback) {
//it gets registered
}

My problem is that I want to register a member function as a callback, something like this

struct MyStruct {
    MyStruct();
    int myCallback(std::string str);
};

MyStruct::MyStruct() {
    registerCallback(&MyStruct::myCallback);
}

int MyStruct::myCallback(std::string str) {
    return 0;
}

Of course, the compiler complains saying

error C2664: 'registerCallback': cannot convert parameter 1 from 'int (__thiscall MyStruct :: *) (std :: string)' to 'Callback'

I look at libraries like function and binding, but none of them seem to be able to do the trick. I searched all over Google for an answer, but I don’t even know what to call it, so it didn’t help much.

Thanks in advance.

+5
6

- , . - this , , .

:

  • , -,
  • - (, static)
  • , , - std::string - boost bind
  • - std::function ( , )
  • , , .
+7

. , MyStruct::myCallback() a static, .

struct MyStruct {
  ...
  static int myCallback(std::string str);
  ^^^^^^
};
+1

- - , . , , , . , -, .

, , - static namespace, oneton, .

, , ( , ).

template <int which_callback>
struct CallbackHolderHack
{
    static int callback_func(std::string str) { dispatchee_->myCallback(str); }
    static MyStruct* dispatchee_;
};

template <int which_callback>
MyStruct* CallbackHolderHack::dispatchee_(0);

:

CallbackHolderHack<0>::dispatchee_ = new MyStruct;
registerCallback(&CallbackHolderHack<0>::callback_func);
+1

++, functor object? std::mem_fun.

. , std::mem_fun ++ 11. std::function , .

. SO , .

0

, ... , Singlton

struct MyStruct {
    static MyStruct& Create() { 
        static MyStruct m; return m;
    }
    static int StaticCallBack(std::string str) { 
        return Create().Callback(str)
    }
    private:
    int CallBack(std::string str);
    MyStruct();
};

, , . callback.

0
class ICallBackInterface
{
public:
    virtual void FireCallBack( std::string& str ) = 0;
};

std::set<ICallBackInterface*> CallBackMgr;

class MyStruct : public ICallBackInterface
{
public:
    MyStruct()
    {
        CallBackMgr.insert( this );
    }

    ~MyStruct()
    {
        CallBackMgr.erase( this );
    }

    virtual void FireCallBack( std::string& str )
    {
        std::cout << "MyStruct  called\n";
    }
};

void FireAllCallBack(std::string& str )
{
    for ( std::set<ICallBackInterface*>::iterator iter = CallBackMgr.begin();
        iter != CallBackMgr.end();
        ++iter)
    {
        (*iter)->FireCallBack( str );
    }
}

-1
source

All Articles