function - 引用类方法

标签 function c++11 reference arguments

我想将对类方法的引用传递给函数。

例如:

#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/

相关文章:

postgresql - 在 postgresql 中返回指数移动平均线快照的最快方法

Javascript:从iframe调用父函数

c++ - std::has_virtual_destructor 是如何实现的?

c# - 命名空间中不存在 Unity 5.3.3 UI

python - 如何获取python中函数内部定义的所有局部变量?

javascript - 为什么两个 if 语句在一个函数中不起作用?

c++ - 视觉 C++ : forward an array as a pointer

c++ - 使用 vector 在初始化列表中 move 构造函数

objective-c - Objective C 类引用作为属性

rust - 我可以避免使用显式生命周期说明符,而是使用引用计数 (Rc) 吗?