samedi 4 juin 2016

C++ - How to implement class with virtual method on the fly

The title is a bit misleading, but I don't know how to phrase the problem in one line.

Basically, I'm using a library that has the definition of this class:

class UCallbackWrapper {
   public:
      virtual UCallbackAction operator ()(const UMessage &)=0;
      virtual ~UCallbackWrapper() {}
};

And I'm using a function of the library that has this declaration:

 UCallbackID setCallback(UCallbackWrapper & callback, const char * tag);

So basically, it receives as argument a member of the class UCallbackWrapper.

If in the c++ file with the main function of the program I declare a function with the right prototype, it lets me pass it to the setCallback function, like this:

UCallbackAction onImageCallback(const UMessage &msg)
{
    // Some code here
}

int main(int argc, char *argv[])
{       
   setCallback(onImageCallback, "something"); // This works
}

Now, I would like to create a class instead, and use the setCallback function inside that class, passing a function that is member of that class. But if I do that, then the prototype of the function goes from

UCallbackAction onImageCallback(const UMessage &msg)

to

UCallbackAction (myClass::*)onImageCallback(const UMessage &msg)

and I can no longer pass that to setCallback.

I tried creating a lambda function, like this:

std::function<UCallbackAction(const UMessage &)> onImageCallback = [&] (const UMessage &msg) -> UCallbackAction {
    // Code here
};

setCallback(onImageCallback, "something");

but still doesn't work, the compiler says:

error: no matching function for call to 'USyncClient::setCallback(std::function&, const char [8])' note: no known conversion for argument 1 from 'std::function' to 'UCallbackWrapper&'

So, I thought about creating a class that inherits from UCallbackWrapper and implements the virtual method (kinda like what I would do in Java), but I don't know how to do that in C++ (or of it's possible).

Can you guys help me out? Or maybe point out something that I'm doing wrong with the lambda function, or a workaround anyway.

Aucun commentaire:

Enregistrer un commentaire