参考class方法
Reference to class method
我想将对 class 方法的引用传递给函数。
例如:
#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
并且您想将 "reference" 传递给特定对象的成员函数。
在这种情况下,您可以使用 lambda:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo
对象被捕获在方括号中(在本例中是通过引用),因此您可以在该特定对象上调用 f
成员函数。
虽然这不是你问题的一部分,但我应该补充一点,通过 const 引用传递 int
并不是很有用,因为那样你不会获得任何性能改进。实际上,您的代码 运行 比按值传递 int
慢。
我想将对 class 方法的引用传递给函数。
例如:
#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
并且您想将 "reference" 传递给特定对象的成员函数。
在这种情况下,您可以使用 lambda:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo
对象被捕获在方括号中(在本例中是通过引用),因此您可以在该特定对象上调用 f
成员函数。
虽然这不是你问题的一部分,但我应该补充一点,通过 const 引用传递 int
并不是很有用,因为那样你不会获得任何性能改进。实际上,您的代码 运行 比按值传递 int
慢。