【问题标题】:Passing const class object to std::function and std::bind lead compilation error将 const 类对象传递给 std::function 和 std::bind 导致编译错误
【发布时间】:2018-11-18 15:05:54
【问题描述】:

const Serviceclassstd::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&amp; 上调用非常量 Serviceclass::getdata。它与 bind、std::function 或提供的代码中的几乎任何东西无关。

标签: c++ c++11 constants std-function stdbind


【解决方案1】:

要么将成员函数设为 const,要么将 Serviceclass 的非 const 对象设为。

//                                        ^^^^^ add const
void Server::getdata(int Id,callback_data)const {
        // callback called with datalist
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2022-01-21
    • 2014-01-22
    • 1970-01-01
    • 2013-02-01
    • 2016-11-13
    相关资源
    最近更新 更多