【问题标题】:c++ closure and std::functionc++ 闭包和 std::function
【发布时间】:2013-10-17 09:12:50
【问题描述】:

我试图弄清楚当与闭包结合使用时,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;
}

【问题讨论】:

  • 一句话:魔术。不过,这都是纯模板代码,因此您可以自己查看
  • 如果你觉得这很有趣,std::bind 会让你头晕目眩。
  • 除了模板之外,还有几个大型 C++ 库是开源的(GCC 通常使用 stdlibc++,clang 通常使用 libc++),因此您甚至可以查看非模板化的代码。

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


【解决方案1】:

这是一个简约的例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多