C++ c++;闭包和std::函数

C++ c++;闭包和std::函数,c++,c++11,closures,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

我试图弄清楚当与闭包结合使用时,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;
}
#包括
int main(int argc,char*argv[])
{
int mybool=5;
自动foo=[&](int-arg){
返回mybool*arg;
};
std::function foo2=foo;
int结果=foo2(42);
返回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;
};
模板
结构分解器;
模板
结构分解器
{
类型def R return_type;
typedef参数类型;
};
模板
构造我的函数
{
typedef typename分解器::return_type return_type;
typedef typename分解器::参数类型参数类型;
返回类型运算符()(参数类型参数)常量{
返回(*impl)(arg);
}
模板
my_函数(从和从)
{
结构ConcreteImpl:Impl
{
typename std::remove_reference::type functor;
ConcreteImpl(From&&functor):functor(std::forward(functor)){
虚拟返回类型运算符()(参数类型参数)常量重写
{
返回函子(arg);
}
};
执行重置(新的ConcreteImpl(std::forward(from));
}
私人:
结构Impl{
虚拟~Impl(){}
虚拟返回类型运算符()(参数类型参数)常量=0;
};
std::唯一的\u ptr impl;
};
核心思想是使用类型擦除来存储实际的闭包,而不知道其类型:请参阅虚拟的
Impl::operator()
和本地定义的特定于类型的holder
ConcreteImpl


一句话:魔法。不过,这只是模板代码,所以你可以自己简单地查看它。如果你发现它有趣,会让你头晕。除了模板之外,还有两个大的C++库,即开源的(通常由GCC使用的STDLBC++),以及通常由CLAN使用的LBC+ +。因此,您甚至可以查看非模板化的代码