C++ std::Bind function instance error with placeholder

120 Views Asked by At

Need help to identify what am I doing wrong.

I am trying to use _1 ,_2 for to find instance of the class object to bind a function.

class CL_2 {

        public:
        void set_item(item_t* item){
        ...
    }
};



class CL_1{

    CL_2** cl_2_inst;
  
    CL_1(){
        for(int i =0; i<2; i++){
            cl_2_inst[i] = new CL_2();
        }
    }

    public :
       CL_2* get_cl_2(int inst_num){ return this->cl_2_inst[inst_num]; }
};



class CL_0{

    CL_1** cl_1_inst;

    CL_0(){
        for(int i =0; i<2; i++){
            cl_1_inst[i] = new CL_1();
        }
    }

    public :
        CL_1* get_cl_1(int inst_num){ return this->cl_1_inst[inst_num]; }


        using cl_type = function<void(int, int, item_t*)>;
        cl_type cl_set_item = std::bind(&CL_2::set_item, get_cl_1(_1)->get_cl_2(_2), _3);


};


int main(){

    CL_0 *cl = new CL_0();
    
    cl->cl_set_item(0, 1, item);

}

I get following compilation error.

rror: cannot convert ‘const std::_Placeholder<1>’ to ‘int’
   36 |   cl_type cl_set_item = std::bind(&CL_2::set_item, get_cl_1(_1)->get_cl_2(_2), _3);
      |                                                             ^~
      |                                                             |
      |                                                             const std::_Placeholder<1>

I was hoping to use arguments (_1/_2) itself to bind to correct instance of function.

If this is not acceptable, can you please recommend how I can achieve this ?

Thanks in advance

1

There are 1 best solutions below

0
molbdnilo On

get_cl_1(_1) and get_cl_1(_1)->get_cl_2(_2) are function calls, and those functions take int arguments, not placeholders.
The arguments to bind must be values, not arbitrary expressions that should be evaluated later. The placeholders can only be passed directly to bind.

There is little point in mucking around with std::bind now that we have lambda functions;

cl_type cl_set_item = [this](int one, int two, item_t* three)
                      { get_cl_1(one)->get_cl_2(two)->set_item(three); };