C++ 将类方法作为函数参数传递
我试图将特定类实例的方法作为参数发送给函数(foo),尽管我一直收到此错误 非静态成员函数的使用无效 (从行foo(a->bar)) 我不知道为什么会出现这个错误?有可能的解决办法吗C++ 将类方法作为函数参数传递,c++,C++,我试图将特定类实例的方法作为参数发送给函数(foo),尽管我一直收到此错误 非静态成员函数的使用无效 (从行foo(a->bar)) 我不知道为什么会出现这个错误?有可能的解决办法吗 #include <iostream> #include <functional> void foo(std::function<void(void)> _func) { _func(); } class A { public: A() {
#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;
}
#包括
#包括
void foo(std::function _func)
{
_func();
}
甲级
{
公众:
()
{
x=5;
}
空条()
{
std::cout您有两个选择:
使用:foo(std::bind(&A::bar,A)):
用法:foo([&a](){a.bar();});
您有两个选择:
使用:foo(std::bind(&A::bar,A)):
用法:foo([&a](){a.bar();});
您的方法与std::function不兼容,即使它看起来像。
每个方法都有一个隐式的第一个参数
你的签名是这样的
void bar(A* this) { /* ... */ }
静态方法不是这种情况,它们类似于类和类的命名空间中的函数
static void bar() { /* ... */ }
将使std::函数饱和
不过,对于我们的示例来说,使用lambda(c++11)很可能是更好的方法。您的方法与std::function不兼容,即使它看起来像。
每个方法都有一个隐式的第一个参数
你的签名是这样的
void bar(A* this) { /* ... */ }
静态方法不是这种情况,它们类似于类和类的命名空间中的函数
static void bar() { /* ... */ }
将使std::函数饱和
不过,对于我们的示例来说,使用lambda(c++11)很可能是更好的方法