2017-02-15 101 views
0

我有一個類,其成員函數我試圖指向,問題是我一直得到這個錯誤reference to non-static member function must be called,從我的理解是,成員函數需要指出。問題是,當我嘗試使用this解決方案,編譯器會抱怨,因爲there is no viable conversion from 'void (Foo::*) (const List&) to std::function<void (const List &)>函子 - >對非靜態成員函數的引用必須調用

這是我Foo類:

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; 
} 

回答

4

,你可以這樣做:

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

或:

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

謝謝!奇蹟般有效。我使用了第一個選項。你能向我解釋嗎? –

+0

你可以看到這個:[link](http://en.cppreference.com/w/cpp/utility/functional/bind) –