[英]std thread call template member function of template class: compiler error
Here is the code. 这是代码。 It does not compile in vs2013, but does compile in gcc4.8
它不在vs2013中编译,但在gcc4.8中编译
error C2665: 'std::thread::thread' : none of the 4 overloads could convert all the argument types 错误C2665:'std :: thread :: thread':4个重载中没有一个可以转换所有参数类型
Since I am using vs2013, can anyone provide workaround? 由于我使用vs2013,任何人都可以提供解决方法吗?
#include <iostream>
#include <thread>
template<typename T>
class TestClass
{
public:
TestClass(){};
~TestClass(){};
T t;
template<typename U>
void fun(U u)
{
std::cout << "fun: " << u << '\n';
}
};
int main()
{
TestClass<double> A;
auto aaa = std::thread(&TestClass<double>::fun<int>, &A, 1);
}
You could simply use a lambda rather than monkeying with member function pointers: 您可以简单地使用lambda而不是使用成员函数指针进行修改:
auto aaa = thread( [&]{ A.fun(1); } );
aaa.join();
There is another way you can achieve above problem,If you would mind ! 还有另一种方法可以实现上述问题,如果您愿意的话! First just look explicit constructor of thread object:
首先看一下线程对象的显式构造函数:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
f - Universal reference for function object. f - 功能对象的通用引用。
args - variadic arguments for function(functor) f . args - 函数的变量参数(仿函数) f 。
(I am not going to explain deeper and deeper about variadic calling used here). (我不会更深入地解释这里使用的可变参数调用)。 So now we know we can deal with functors therefore, Define a functor(function object) like below :
所以现在我们知道我们可以处理仿函数, 定义一个仿函数(函数对象),如下所示:
template<typename T>
class TestClass
{
public:
TestClass(){};
~TestClass(){};
T t;
template<typename U>
void operator()(U u1,U u2){
std::cout << "fun: " << u1*u2 << '\n';
}
};
int main()
{
TestClass<double> A;
auto aaa = std::thread(A,1,100);// calling functor A(1,100)
aaa.join()
//or if you can move object from main thread to manually created thread aaa ,it's more elegant.
auto aa = std::thread(std::move(A),1,100);
aa.join();
A(1, 99);
system("Pause");
return 0;
}
//Please notice here I've not used any locker guard system. //请注意这里我没有使用任何储物柜防护系统。 If you use static function you don't have to bind respective instance each time this may change your expected run-time behavior therefore you have to managed,
如果您使用静态函数,则每次这可能会改变您的预期运行时行为时不必绑定相应的实例,因此您必须进行托管,
template<typename U>
static void fun(U u)
{
std::cout << "fun: " << u << '\n';
}
then invoke the function,
int main()
{
TestClass<double> A;
auto aaa = std::thread(&TestClass<double>::fun<int>, 1);
system("Pause");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.