gpt4 book ai didi

c++ - 模板函数在作为线程调用时不会编译

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:35 25 4
gpt4 key购买 nike

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

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

这不会编译;我得到:

error: no matching function for call to âstd::thread::thread(, unsigned int&)â

如果我删除它编译的模板,如果我将函数调用更改为标准函数调用而不是线程(仍然使用模板)它编译。<​​/p>

谁知道这是为什么?

我使用的是 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()

最佳答案

没有名为 Threader 的函数。当你写 Threader<int>或其他东西,然后编译器创建一个函数。如果你再写 Threader<float> ,然后编译器创建一个新函数。您可以提供默认模板参数,也可以在调用时为其提供参数。

template <class TYPE_size=int>

thread one(Threader<int>, counter);

关于c++ - 模板函数在作为线程调用时不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8342839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com