将函数转发到c ++ 11中的lambda表达式

use*_*183 6 c++ lambda c++11

对于C++ 11中的Packaged_Task实现,我希望实现我在下面的C++ 14代码中所表达的内容.换句话说,我想转发一个lambda表达式.

template<class F>
Packaged_Task(F&& f) {
    Promise<R> p;
    _future = p.get_future();

     auto f_holder = [f = std::forward<F>(f)]() mutable { return std::move(f); };
 ///...
Run Code Online (Sandbox Code Playgroud)

我知道移植到lambda的变通方法(但不幸的是这个变通方法需要一个默认的可构造对象,在我的例子中,对象通常是没有default-constructor的lambda表达式)

Aru*_*nmu 3

创建一个在复制构造期间进行移动的包装结构怎么样:(。(我知道这很糟糕,让我记住auto_ptr

template <typename F>
struct Wrapped {
  using Ftype = typename std::remove_reference<F>::type;
  Wrapped(Ftype&& f): f_(std::move(f)) {}

  Wrapped(const Wrapped& o): f_(std::move(o.f_)) {}

  mutable Ftype f_; 
};

template<class F>
Packaged_Task(F&& f) {
    Promise<R> p;
    _future = p.get_future();
     Wrapped<std::remove_reference<decltype(f)>::type> wrap(std::forward<F>(f));

     auto f_holder = [wrap]() mutable { return std::move(wrap.f_); };
Run Code Online (Sandbox Code Playgroud)

这只是一个粗略的想法。未编译或测试。

注意:我以前见过这种技术,不记得它是在 SO 本身上还是在某个博客上。