我正在使用Visual Studio 2013,想要实现这行代码
f = p.get_future();
auto task =[f = std::move(f)](){
//use f
};
我知道这里有一个解决方案(链接),但不幸的是,在VS2013下它并不能通过编译(
错误C2558:没有可用的复制构造函数
)。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中,您可能需要在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()
调用 -- ->*
操作将 lambda 绑定并在调用时传递 futures。
实时示例。
请注意,这解决了将 future 移动到 lambda 中的问题。如果您想将 lambda 存储在 std::function
中,这将无法帮助您,因为函数必须可复制。
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))};
}
operator()
。但是,首先使用上述技术将一个 future 移动到 lambda 中,然后将该 lambda 包装在共享函数中以传递给 std::function
是荒谬的:直接在一开始使用 shared_future
即可。packaged_task
只需要移动,但我不确定 MSVC2013 是否支持该要求。
std::function
? - Yakk - Adam Nevraumont