我想使用 packaged_tasks 将任务添加到容器中。我创建了一个任务,将其绑定到一个数字并尝试将其推送到我的双端队列中。我在 push_back 上收到编译器错误 C2280 (VS2013)。这是代码:
void DoTask( int i )
{
std::cout << "int value: " << i << std::endl;
}
std::deque< std::packaged_task< void() > > task_q;
int _tmain(int argc, _TCHAR* argv[])
{
std::packaged_task< void() > t( std::bind( DoTask, 3 ) );
task_q.push_back( t ); // <-- C2280 error
return 0;
}
我从一个名为“C++ Threading #9: packaged_task”的 YouTube Bo Qian 讲座中获得了这个示例代码。这是一些错误代码文本:
error C2280:
'std::packaged_task<void (void)>::packaged_task(const std::packaged_task<void (void)> &)' : attempting to reference a deleted function... see declaration of 'std::packaged_task<void (void)>::packaged_task'...while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
1> with
1> [
1> _Ty=std::packaged_task<void (void)>"
这是两次更正后的代码(移动任务和非空返回值):
int DoTask( int i ) // non-void return value
{
return i;
}
std::deque< std::packaged_task< int() > > task_q; // bind eliminates need for arg (Bo Qian lecture)
int _tmain( int argc, _TCHAR* argv[] )
{
std::packaged_task< int() > t( std::bind( DoTask, 3 ) ); // bind eliminates need for arg
task_q.push_back( std::move( t ) ); // <-- move not copy
return 0;
}