【发布时间】:2018-11-18 15:05:54
【问题描述】:
当 const Serviceclass 在 std::function 中使用时会导致编译错误。 如果删除 const 则复杂化成功。
代码流 : Client::GetValue() 被调用,它调用 Server::datalist()
问题:为什么我不能在 Serviceclass 上使用 const?
服务器端
// vvvvv (if const remove then compliation success.)
typedef std::function<void(int, Status, const Serviceclass&)>
Callback;
//SECOND INVOKED
void Server::datalist(int Id, sessionId,Callback callback) {
std::unique_ptr<Serviceclass> ServiceObj = Serviceclass::create();
callback(request_id, RESULT,*ServiceObj.get());
}
typedef std::vector<std::string> dataList;
typedef std::function<void(int, Status, const dataList&)>callback_data;
//FOURTH INVOKED
void Server::getdata(int Id,callback_data){
// callback called with datalist
}
客户端
//FIFTH INVOKE
void Client::Foo(int Id,Status,const dataList& data){
//impl
}
//THIRD INVOKED
void Client::Boo(int Id,
Status,
const Serviceclass& Serviceclass){
// ^^^^^ (if const remove then compliation success.)
Serviceclass.getdata(123,
std::bind(&Client::Foo, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
}
//FIRST INVOKED
void Client::GetValue() {
int Id = 123;
serverobj->datalist(
Id, sessionId,
std::bind(&Client::Boo, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
}
错误
In member function 'void Client::Boo(int, Status, const Serviceclass&)':
mycode.cc:68:76: error: passing 'const Serviceclass&' as 'this' argument discards qualifiers [-fpermissive]
std::placeholders::_2, std::placeholders::_3));
【问题讨论】:
-
你能给我们确切的错误信息吗?
-
@HolyBlackCat 我添加了编译错误。请看一看。
-
错误似乎指向
Client::Boo内部,但您没有包含函数体。它指向哪条线? -
看起来 Serviceclass::getdata 不是 const 成员函数。
-
您不能在非常量对象上调用非常量成员函数。在这里,您尝试在
const Serviceclass&上调用非常量Serviceclass::getdata。它与 bind、std::function 或提供的代码中的几乎任何东西无关。
标签: c++ c++11 constants std-function stdbind