有两个类的服务器和客户端。客户端调用服务器上的方法 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> >&)>}’
答案 0 :(得分:3)
如果我们将std::function
和实际函数彼此相邻,那么很容易发现差异(经过重新格式化以更好地显示它):
// vvvvv
typedef std::function<void(int , Status , const datalist&)> Callback;
void clientfun1( int req_id, Status status, datalist& datas) {
// ^^^^^
现在我们可以看到,对于std::function
对象,最后一个参数是对 常数 datalist
的引用,而在{{ 1}}函数是 not 常量。
这会使两种函数类型不同,从而导致错误。