-2

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

273K
  • 29,503
  • 10
  • 41
  • 64
bh987
  • 19
  • 3
  • 1st of all why so many raw pointers in the code? Not a good practice. 2nd: Not `delete`ing the `new`d pointers leads to memory leak. 3rd: if you need C++ lambdas don't confuse them with `std::bind` library. – Red.Wave May 06 '23 at 11:01
  • Just a psuedo code to show the issue. I am still little lost on when to use bind vs lambda. – bh987 May 06 '23 at 15:12
  • It looks like you're totally lost. I am afraid bind vs lambda is not the biggest issue here; because compiler is preventing a runtime disaster by failing at compilation. You're gonna dive into the ocean of runtime errors and bugs, if you don't learn the fundamentals. Raw pointers and manual memory management is not the right path to start with. – Red.Wave May 06 '23 at 19:38

1 Answers1

4

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); };
molbdnilo
  • 64,751
  • 3
  • 43
  • 82