【问题标题】:Passing a class method as function argument将类方法作为函数参数传递
【发布时间】:2016-08-07 09:23:01
【问题描述】:

我正在尝试将特定类实例的方法作为参数发送给函数 (foo),尽管我不断收到此错误

非静态成员函数的使用无效...

(来自 foo(a->bar) 行)

我不确定为什么会出现此错误?是否有可能的解决方法?

#include <iostream>
#include <functional>

void foo(std::function<void(void)> _func)
{
    _func();
}

class A
{
public:
    A()
    {
        x = 5;
    }
    void bar()
    {
        std::cout << x << std::endl;
    }

private:
    int x;
};

int main() {
    A a;
    foo(a->bar);
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    你有两个选择:

    1. 使用std::bind:foo(std::bind(&amp;A::bar, a)):

    2. 使用lambdas:foo([&amp;a]() { a.bar(); });

    【讨论】:

      【解决方案2】:

      您的方法与 std::function 不兼容,即使看起来像。 每个方法都有一个隐式的第一个参数 this。

      所以你的签名看起来像这样

      void bar(A* this) { /* ... */ }
      

      这不是静态方法的情况。这些就像类的命名空间中的函数和

      static void bar() { /* ... */ } 
      

      会使 std::function 饱和。

      不过,对于你的例子来说,使用 lambda (c++11) 很可能是更好的方法。

      【讨论】:

        猜你喜欢
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        • 2016-10-14
        • 2011-08-18
        • 2016-11-02
        • 2011-09-04
        • 1970-01-01
        相关资源
        最近更新 更多