【发布时间】:2014-09-18 09:35:59
【问题描述】:
在下面的代码中,我有一个接受“通用引用”(F&&) 的函数。该函数还有一个内部类,它在其构造函数中接受F&& 的对象。 F&& 在那时仍然是通用参考吗? IE。 F 仍然被认为是推导类型吗?
也就是说,我应该在构造函数初始化列表中使用std::forward<F>还是std::move?
#include "tbb/task.h"
#include <iostream>
#include <future>
template<class F>
auto Async(F&& f) -> std::future<decltype(f())>
{
typedef decltype(f()) result_type;
struct Task : tbb::task
{
Task(F&& f) : f_(std::forward<F>(f)) {} // is forward correct here?
virtual tbb::task* execute()
{
f_();
return nullptr;
}
std::packaged_task<result_type()> f_;
};
auto task = new (tbb::task::allocate_root()) Task(std::forward<F>(f));
tbb::task::enqueue(*task);
return task->f_.get_future();
}
int main()
{
Async([]{ std::cout << "Hi" << std::endl; }).get();
}
【问题讨论】:
-
酷孩子们称他们为forwarding references 现在不是通用参考。 (costhere ain't no such thing as a universal reference.)
标签: c++ forward forwarding perfect-forwarding forwarding-reference