您可以使用shared_future
。那是最简单的。
然而,这并不能帮助你移动。如果您确实需要搬家,我们可以在专业人士的帮助下进行move_helper
功能和类别:
template<class T, class F=void>
struct move_helper_t {
T t;
F f;
template<class...Args>
auto operator()(Args&&...args)
->typename std::result_of< F&(T&, Args...) >::type
{
return f(t, std::forward<Args>(args)...);
}
// force right-associativity of `->*`, and
// invert the stack to get the arguments in the "right" order:
template<class F1,
class R0=move_helper_t< T, typename std::decay<F1>::type >
>
auto operator->*(F1&& f1)
-> decltype(
std::declval<F>()->*
std::declval<R0>()
)
{
return
std::move(f)->*
R0{ std::forward<T>(t), std::forward<F1>(f1) };
}
};
template<class T>
struct move_helper_t<T,void> {
T t;
template<class F>
auto operator->*(F&& f)
-> move_helper_t<T, typename std::decay<F>::type>
{
return {std::forward<T>(t), std::forward<F>(f)};
}
};
template<class T>
move_helper_t<std::decay_t<T>>
move_helper( T&& t ) {
return {std::forward<T>(t)};
}
在 MSVC 2013 中,您may必须声明一个构造函数move_helper_t
。我不记得他们写得有多好return {}
代码是。
f = p.get_future();
task =
move_helper(std::move(f)) ->*
[](std::future<int>& f){
//use f
};
->*
绑定move_helper
到 lambda。然后它返回一个可调用对象,该对象将被传递给std::future<int>&
作为调用时的第一个参数。
由于它的编写方式,您甚至可以将其链接起来:
auto f = p.get_future();
auto f2 = p2.get_future();
task =
move_helper(std::move(f)) ->*
move_helper(std::move(f2)) ->*
[](std::future<int>& f, std::future<char>& f2){
//use f
};
将多个参数移至 lambda 中。
在这两种情况下,task
可以通过调用task()
-- the ->*
操作将 lambda 绑定起来并在调用时传递 future。
实例 http://coliru.stacked-crooked.com/a/d8dbc52ac651cca7.
请注意,这解决了将 future 移入 lambda 的问题。如果你想将 lambda 存储在std::function
, this 不会帮助你,因为函数必须是可复制的。
template<class F>
struct shared_function {
std::shared_ptr<F> pf;
template<class ...Args>
typename std::result_of<F&(Args...)>::type
operator()(Args&&...args) const {
return (*pf)(std::forward<Args>(args)...);
}
};
template<class F,
class dF=typename std::decay<F>::type
>
shared_function< dF >
make_shared_function( F&& f ) {
return {std::make_shared<dF>(std::forward<F>(f))};
}
这需要一个可移动的 lambda 并将其包装在一个共享指针中并公开operator()
为你。但首先采取future
通过上述技术将其移动到 lambda 中,然后将该 lambda 包装在共享函数中以将其传递给std::function
很荒谬:只需使用shared_future
首先。
顺便说一句,理论上,packaged_task
只需要移动,但我不确定MSVC2013是否支持该要求。