assigning std::function to a member function

被刻印的时光 ゝ 提交于 2019-12-07 13:38:19

问题


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.


回答1:


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>



来源:https://stackoverflow.com/questions/12833707/assigning-stdfunction-to-a-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!