Search code examples
c++c++11constantsstd-functionstdbind

Passing const class object to std::function and std::bind lead compilation error


When const Serviceclass used in std::function leads to compilation error. If remove const the complication is successful.

Code Flow : Client::GetValue() is called which calls on Server::datalist()

QUESTION : Why can't i use const on Serviceclass ?

SERVER SIDE

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

CLIENT SIDE

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

ERROR

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

Solution

  • Either make member function const or make non const object of Serviceclass.

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