【问题标题】:assigning std::function to a member function将 std::function 分配给成员函数
【发布时间】:2012-10-11 06:45:53
【问题描述】:
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);
  }
};

这不起作用。我收到note: no known conversion for argument 1 from ‘&lt;unresolved overloaded function type&gt;’ to ‘std::function&lt;void(int)&gt;’ 和其他错误。

如果我将print_num 的定义放在课堂之外。一切正常。我尝试添加&amp;A::A::this. 没有任何帮助。

【问题讨论】:

    标签: c++ c++11 std-function


    【解决方案1】:

    print_num 是一个非静态成员函数,这意味着它具有A* 类型的隐式第一个参数。例如,您可以使用 lambda 传递它:

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

    或使用bind,看这里

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

    【讨论】:

    • ehh,我认为 std::function 应该让事情变得更容易:-(
    • setFunction( [this] (int i) { this-&gt;print_num (i); } ); 也有效
    • 使用[this] 会复制对象,因此您可能需要[&amp;this],或者只需要[&amp;]
    • 是吗? this 是一个指针,所以使用 [this] 应该复制指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多