You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is a question and I hope this is the right place for this. I had a need for a C++ non static member function as callback. Being relatively new to C++ Google lead me to using a "trampoline" approach to get around this, i.e. declare a global callback function and then pass through a pointer to the instance of the class using void*. Then static_cast this pointer back to the correct class type. Much like this.
This however required me to add this second parameter to the dispatch signatures in the easywsclient.hpp class. Is there another way to do this without changing the code?
I'm using C++98 with GNU compiler.
The text was updated successfully, but these errors were encountered:
Hi wezside! It is possible to bind a C++ method to a class instance and use it as a callback by using a "functor". No need to rewrite the dispatch signature, just need to bind the method to a class instance, for example,
class Functor {
MyClass * instance;
public:
Functor(MyClass * instance) : instance(instance) {
}
void operator()(const std::string& message) {
instance->memberFunction(message);
}
};
int main() {
// ...
MyClass myClass;
Functor functor(&myClass); // <-- a pre-C++11 way to bind instance+method
webSocket->dispatch(functor); // <-- no need to change signature
// ...
}
It is nicer if you can use a library that provides this binding capability for you though. Some libraries are:
This is a question and I hope this is the right place for this. I had a need for a C++ non static member function as callback. Being relatively new to C++ Google lead me to using a "trampoline" approach to get around this, i.e. declare a global callback function and then pass through a pointer to the instance of the class using void*. Then static_cast this pointer back to the correct class type. Much like this.
This however required me to add this second parameter to the dispatch signatures in the easywsclient.hpp class. Is there another way to do this without changing the code?
I'm using C++98 with GNU compiler.
The text was updated successfully, but these errors were encountered: