C++ 闭包和 std::function

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

我正在尝试弄清楚 std::function 与闭包结合使用时发生了什么。我还不能全神贯注,例如:正在调用什么构造函数? 任何人都可以发布一个工作示例来替换 std::function 以支持以下示例中所需的功能吗?

#include <functional>

int main(int argc, char* argv[])
{
    int mybool = 5;

    auto foo = [&] (int arg) {
        return mybool * arg;
    };

    std::function<int(int)> foo2 = foo;

    int result = foo2(42);

    return 0;
}

最佳答案

这是最简单的例子:

template <class F>
struct Decomposer;

template <class R, class A>
struct Decomposer<R (A)>
{
  typedef R return_type;
  typedef A argument_type;
};


template <class F>
struct my_function
{
  typedef typename Decomposer<F>::return_type return_type;
  typedef typename Decomposer<F>::argument_type argument_type;

  return_type operator() (argument_type arg) const {
    return (*impl)(arg);
  }

  template <class From>
  my_function(From &&from)
  {
    struct ConcreteImpl : Impl
    {
      typename std::remove_reference<From>::type functor;
      ConcreteImpl(From &&functor) : functor(std::forward<From>(functor)) {}
      virtual return_type operator() (argument_type arg) const override
      {
        return functor(arg);
      }
    };
    impl.reset(new ConcreteImpl(std::forward<From>(from)));
  }

private:
  struct Impl {
    virtual ~Impl() {}
    virtual return_type operator() (argument_type arg) const = 0;
  };

  std::unique_ptr<Impl> impl;
};

核心思想是使用类型删除来存储实际的闭包而不知道其类型:参见虚拟Impl::operator() 和本地定义的类型-具体持有人 ConcreteImpl.

Live example

关于C++ 闭包和 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19422547/

相关文章:

c++ - 在 C++ 中包装多个库的策略

c++ - 浮点加法提升为双倍?

c++ - 为什么类的析构函数被调用了两次?共享指针

c++ - 根据运行时决策组合不同的迭代器

c# - 我可以 PInvoke C++ 可执行文件但不能共享库

c++ - 具有单个参数的 std::min() 的实现是什么?

c++ - 多种类型的类模板特化

ios - 带参数的 Swift 传递闭包

javascript - 动态添加的对象属性未在 Javascript 中添加

java - 在 Java 中引用匿名内部类中封闭类的非最终字段