Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non static member function as callback #28

Closed
wezside opened this issue Mar 20, 2014 · 2 comments
Closed

Non static member function as callback #28

wezside opened this issue Mar 20, 2014 · 2 comments

Comments

@wezside
Copy link

wezside commented Mar 20, 2014

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.

@dhbaird
Copy link
Owner

dhbaird commented Mar 21, 2014

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:

http://www.boost.org/doc/libs/1_55_0/libs/bind/bind.html (if you do not have C++11)

I know you said you are using C++98, but if you had the luxury of C++11, then here are some more options:
http://en.cppreference.com/w/cpp/utility/functional/function (if you have C++11)
http://en.cppreference.com/w/cpp/utility/functional/bind (if you have C++11)

Hope this helps. Definitely feel free to ask if this raises another question :)

@wezside
Copy link
Author

wezside commented Mar 22, 2014

That's awesome. Didn't know about Functors and their use. Thanks!

@wezside wezside closed this as completed Mar 22, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants