使用 std::bind 和 std::function 时回调失败

callbacks fails when std::bind and std::function used

有两个class 服务器和客户端。客户端在服务器上调用方法 datas()。服务器使用 datacallback().

用数据列表响应调用者

当调用 serverobj.datas() 时,我在函数 clientfun2 中看到编译时错误。请帮助修复它。

#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <vector>

enum Status { SUCCESS, FAILED, UNKOWN };

typedef std::vector<std::string> datalist;

class server {
 public:
  typedef std::function<void(int, Status, const datalist&)> Callback;
  void datas(int request_id, Callback datacallback) {
    datalist data; //here data is inserted and set to caller
    std::cout << "Invoked datas method\n";
    datacallback(123, SUCCESS, data); // sending back to caller
  }
};

class client {
 public:
  void clientfun1(int req_id, Status status, datalist& datas) {
    std::cout << "Invoked clientfun1\n";
  }

  void clientfun2(server serverobj) {
    serverobj.datas(123,
                    std::bind(&client::clientfun1, this, std::placeholders::_1,
                              std::placeholders::_2, std::placeholders::_3));  /*Here the error comming pls help to fix */
  }
};

int main() {
  server serverobj;
  client clientobj;
  clientobj.clientfun2(serverobj);
}

****文本格式错误****

bind.cc: In member function ‘void client::clientfun2(server)’:
bind.cc:30:76: error: no matching function for call to ‘server::datas(int, std::_Bind_helper<false, void (client::*)(int, Status, std::vector<std::__cxx11::basic_string<char> >&), client*, const std::_Placeholder<1>&, const std::_Placeholder<2>&, const std::_Placeholder<3>&>::type)’
                               std::placeholders::_2, std::placeholders::_3));
                                                                            ^
bind.cc:14:8: note: candidate: void server::datas(int, server::Callback)
   void datas(int request_id, Callback datacallback) {
        ^
bind.cc:14:8: note:   no known conversion for argument 2 from ‘std::_Bind_helper<false, void (client::*)(int, Status, std::vector<std::__cxx11::basic_string<char> >&), client*, const std::_Placeholder<1>&, const std::_Placeholder<2>&, const std::_Placeholder<3>&>::type {aka std::_Bind<std::_Mem_fn<void (client::*)(int, Status, std::vector<std::__cxx11::basic_string<char> >&)>(client*, std::_Placeholder<1>, std::_Placeholder<2>, std::_Placeholder<3>)>}’ to ‘server::Callback {aka std::function<void(int, Status, const std::vector<std::__cxx11::basic_string<char> >&)>}’

如果我们将 std::function 和实际函数放在一起,很容易看出差异(重新格式化以更好地显示):

//                                                    vvvvv
typedef std::function<void(int       , Status       , const datalist&)> Callback;
void clientfun1(           int req_id, Status status,       datalist& datas) {
//                                                    ^^^^^

现在我们可以看到 std::function 对象的最后一个参数是对 constant datalist,而在 clientfun1 函数中它是 not 常量。

这使得两个函数类型不同,从而导致您的错误。