Search code examples
c++functionclassfunctor

Functor -> reference to non-static member function must be called


I have a class whose member function I am trying to point to, problem is I keep getting this error reference to non-static member function must be called which from my understanding is that a member function needs to be pointed to. The problem is, when I try to use this solution, the compiler complains because there is no viable conversion from 'void (Foo::*) (const List&) to std::function<void (const List &)>

This is my Foo class:

class Foo {
public:
  int Run( int port);
  void HandleRequest(HTTPServerRequest* request);

private:
    int num_ports;
    void callback_method(const List& );

};  //class Foo

void Foo::HandleRequest(HTTPServerRequest* request){
std::function<void (const List&)> functor = callback_method;
}

Solution

  • you can do like this:

    void Foo::HandleRequest(HTTPServerRequest* request){
        std::function<void (const List&)> functor =
            std::bind(&Foo::callback_method, this, std::placeholders::_1);
    }
    

    or:

    void Foo::HandleRequest(HTTPServerRequest* request){
        std::function<void (const List&)> functor = 
            [this](const List& list){callback_method(list);};
    }