gpt4 book ai didi

c++ - thread::hardware_concurrency() 作为模板参数

转载 作者:行者123 更新时间:2023-11-28 05:04:19 26 4
gpt4 key购买 nike

我有一个模板类,它有一个用于线程数的无符号整型参数。我想用它为线程创建一个静态数组。

我不能使用 std::thread::hardware_concurrency() 作为默认值,

template <typename T, size_t num_threads = std::thread::hardware_concurrency()>
class Some_class{
T values[num_threads];
...
}

也不将其作为参数提供给我的类。

template <typename T, size_t num_threads>
class Some_class{
T values[num_threads];
...
}

Some_class<int,std::thread::hardware_concurrency()> instance;

问题是 std::thread::hardware_concurrency() 的返回值不是 const。

编译器说:

error: call to non-constexpr function ‘static unsigned int std::thread::hardware_concurrency()’

note: in template argument for type ‘long unsigned int’

是否有另一种静态方法来获取我的模板的可用线程数?

最佳答案

Is there another static way to get the number of available threads for my template?

答案是,因为std::thread::hardware_concurrency()不是 constexpr 函数(并发线程的数量可能因程序运行的系统而异,所以它绝对合乎逻辑,对吧?),但 num_threads 必须是用编译时常量初始化。

您可能会处理一些变通方法,例如使用 std::vector 而不是数组:

template <typename T>
class SomeClass {
public:
SomeClass()
: values(std::thread::hardware_concurrency())
{}

private:
std::vector<T> values;
};

关于c++ - thread::hardware_concurrency() 作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212509/

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