c++ - 通过 std::function 引用仿函数

标签 c++ c++11 std-function

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

#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模板函数创建reference wrapper对于您的实例:

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object.

Function templates ref and cref are helper functions that generate an object of type std::reference_wrapper, using template argument deduction to determine the template argument of the result.

你会这样使用它:

t.add(std::ref(t));

关于c++ - 通过 std::function 引用仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336790/

相关文章:

c++ - std::bind 和函数模板

c++ - 带有 unique_ptr 参数的 std::function

c++ - 将从一个函数返回的 vector 传递给另一个函数

c++ - 为什么我会收到内存错误?

c++ - 无法将C共享库链接到C++程序

c++ - QFileInfo 和 UTF-8

c++ - 缺少用于 map 初始化的构造函数

c++ - 将 std::weak_ptr 传递给函数有用吗?

c++ - 组合的基于范围的 for 循环

c++ - std::function 模板参数解析