C++ 返回可中断线程的函数
我询问了一个关于创建一个函数的问题,该函数指定了一个线程要与其参数一起运行的函数,我希望传递重载函数的名称作为线程应该运行的函数,并让线程根据我传递的参数类型选择适当的函数。例如:C++ 返回可中断线程的函数,c++,c++11,C++,C++11,我询问了一个关于创建一个函数的问题,该函数指定了一个线程要与其参数一起运行的函数,我希望传递重载函数的名称作为线程应该运行的函数,并让线程根据我传递的参数类型选择适当的函数。例如: void MyThreadFunc(CObject& obj) {} // Should be called when passing an lvalue void MyThreadFunc(CObject&& obj) {} // Should be called when passing
void MyThreadFunc(CObject& obj) {} // Should be called when passing an lvalue
void MyThreadFunc(CObject&& obj) {} // Should be called when passing an rvalue
答案是,我应该指定调用线程创建函数时线程应作为模板参数运行的函数类型:
template<typename FunctionType, typename ...Args>
void StartDetachedThread(FunctionType func, Args&&... args)
{
thread([&]()
{
func(forward<Args>(args)...);
}).detach();
}
CObject object;
StartDetachedThread<void (CObject&)>(MyThreadFunc, std::ref(object)); // Calls MyThreadFunc(CObject&)
CObject object2;
StartDetachedThread<void (CObject&&)>(MyThreadFunc, std::move(object2)); // Calls MyThreadFunc(CObject&&)
VS 2017对上述线路的投诉:
'void (CObject &&)': cannot convert argument 1 from 'CObject' to 'CObject &&'
You cannot bind an lvalue to an rvalue reference
现在,我可能已经看这个太久了,但我不明白问题所在。有人能温和地解释一下吗?您忘了在
CreateThread()中完美地转发args
:
模板
可中断线程CreateThread(FunctionType&&f,Args&&…Args)
{
返回可中断_线程(std::forward(f),std::forward(args)…);
}
如果不这样做,args
将从右值引用转换为左值引用,以便传递给interruptable\u thread
,这将不起作用
还要注意:避免在Visual Studio中使用名称CreateThread
,因为已经有一个名为CreateThread
的WinAPI,这可能会导致冲突
CObject o2;
interruptible_thread thr = CreateThread<void (CObject&&)>(MyThreadFunc, std::move(o2));
'void (CObject &&)': cannot convert argument 1 from 'CObject' to 'CObject &&'
You cannot bind an lvalue to an rvalue reference
template<typename FunctionType, typename... Args>
interruptible_thread CreateThread(FunctionType&& f, Args&&... args)
{
return interruptible_thread(std::forward<FunctionType>(f), std::forward<Args>(args)...);
}