我想将对类方法的引用传递给函数。
例如:
#include <functional>
struct Foo
{
int f(const int& val) const
{
return val+2;
}
};
int caller(const std::function<int(const int&)>& f)
{
return f(1);
}
int main()
{
caller([](const int& val){return val+2;}); // OK
Foo foo;
caller(foo.f); // WRONG
return 0;
}
如何修复 caller() 的第二次调用(注意:Foo:f() 不是静态的)?
最佳答案
在您的情况下,函数f
不使用Foo
的任何成员,因此可以将其声明为static
static int f(const int& val)
并传递为:
caller(&Foo::f);
但假设 f
不能声明为 static
并且您希望将“引用”传递给特定对象的成员函数。
在这种情况下你可以使用 lambda:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo
对象被捕获在方括号中(在本例中是通过引用),以便您可以在该特定对象上调用 f
成员函数。
尽管这不是您问题的一部分,但我应该补充一点,通过 const 引用传递 int
并不是真正有用,因为这样您不会获得任何性能改进。实际上,您的代码运行速度会比按值传递 int
慢。
关于function - 引用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31188636/