通过 std::function 进行函子引用

2024-05-09

基本上,我希望有以下语义:

#include <functional>
#include <iostream>

class test
{
  public:
    void add(std::function<void()> f)
    {
      f();
    }

    void operator()()
    {
      ++x;
    }

    int x = 33;
};

int main()
{
  test t;
  t.add(t);
  // wanted: x == 34 instead: x == 33 since add(t) copies it
}

我了解 std::function 包装了可调用对象的副本,但是有没有办法使用 std::function 获取对可调用对象的引用?


您想使用std::ref http://en.cppreference.com/w/cpp/utility/functional/ref模板函数来创建参考包装器 http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper对于你的例子:

std::reference_wrapper是一个类模板,它将引用包装在 可复制、可分配的对象。

函数模板ref and cref是生成一个辅助函数 类型的对象std::reference_wrapper,使用模板参数 推导以确定结果的模板参数。

你可以像这样使用它:

t.add(std::ref(t));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 std::function 进行函子引用 的相关文章

随机推荐