Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning std::function to a member function

class A {
public:
  std::function<void(int)> f_;
  void print_num(int i) {
    cout << i;
  }
  void setFuntion(std::function<void(int)> f) {
    f_=f;
  }
  void run() {
    setFunction(print_num);
  }
};

this doesn't work. i get note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘std::function<void(int)>’ and other errors.

If I put the definition of print_num outside of the class. everything works. i tried adding &A::, A:: and this. nothing helped.

like image 606
kirill_igum Avatar asked Jul 19 '26 14:07

kirill_igum


1 Answers

print_num is a non-static member function, which means that it has an implicit first argument of type A*. You can, for instance, pass that by using a lambda:

void run() { 
    auto myself = this;
    setFunction( [myself] (int i) { myself->print_num (i); } ); 
} 

or use bind, see here

c++ Trouble casting overloaded function: <unresolved overloaded function type>

like image 110
JohnB Avatar answered Jul 21 '26 04:07

JohnB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!