调用线程时,模板函数不会编译

Col*_*mbo 7 c++ multithreading templates c++11

我有一个与模板函数和线程有关的问题:

template <class TYPE_size>
void Threader(TYPE_size counter)
{
    counter++;
}
int main()
{
    unsigned int counter = 100;
    thread one(Threader,counter);
    one.join();    
    cout << counter;
}
Run Code Online (Sandbox Code Playgroud)

这不编译; 我明白了:

错误:没有匹配函数来调用âstd:: thread :: thread(,unsigned int&)â

如果我删除它编译的模板,如果我将函数调用更改为标准函数调用而不是线程(仍使用模板),则编译.

有人知道为什么吗?

我正在使用Centos5 64位.

 error: no matching function for call to âstd::thread::thread(<unresolved overloaded function type>, unsigned int&)â
/usr/lib/gcc/x86_64-redhat-linux6E/4.4.0/../../../../include/c++/4.4.0/thread:124: note: candidates are: std::thread::thread(std::thread&&)
/usr/lib/gcc/x86_64-redhat-linux6E/4.4.0/../../../../include/c++/4.4.0/thread:122: note:                 std::thread::thread(const std::thread&)
/usr/lib/gcc/x86_64-redhat-linux6E/4.4.0/../../../../include/c++/4.4.0/thread:121: note:                 std::thread::thread()
Run Code Online (Sandbox Code Playgroud)

Col*_*lin 10

没有名为Threader的函数.当你写Threader<int>或什么时,编译器创建一个函数.如果然后编写Threader<float>,则编译器会创建一个新函数.您可以提供默认模板参数,也可以在调用时为其指定参数.

template <class TYPE_size=int>
Run Code Online (Sandbox Code Playgroud)

要么

thread one(Threader<int>, counter);
Run Code Online (Sandbox Code Playgroud)


Mic*_*idl 5

您缺少模板的参数列表。

尝试:

 unsigned int counter = 100;
 thread one(Threader<unsigned int>,counter);
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用 c++x0/c++11 标准,请为您的模板提供标准类型,例如:

template <typename TYPE_size = unsigned int>
void Threader(TYPE_size counter)
{
    counter++;
}
int main()
{
    unsigned int counter = 100;
    thread one(Threader<>,counter);
    one.join();    
    cout << counter;
}
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 5

我冒昧地提供各种修复来实现我认为的预期行为:

#include <thread>

template <typename T>
void Threader(T & counter)    // take by reference!
{
   counter++;
}

int main()
{
   unsigned int counter = 100;
   std::thread one(Threader<unsigned int>,   // specify template *instance*
                   std::ref(counter) );      // pass variable as reference
   one.join();
   return counter;
}
Run Code Online (Sandbox Code Playgroud)

  • +1 注意在原始示例中`counter` 不会改变。 (2认同)