如何将无符号参数传递给模板

How to pass an unsigned argument to a template?

本文关键字:参数传递 无符号      更新时间:2023-10-16

我有两个文件-其中一个是我传递给模板的无符号参数,另一个包含模板声明和定义。

/*File1.cc */
#include "File2.h"
int main()
{
    unsigned n = 10;
    ThreadPool<n> pool;  //Error
.....
}


/* File_2.h */
....
namespace nbsdx {
namespace concurrent {
template <unsigned ThreadCount>
class ThreadPool {
    std::array<std::thread, ThreadCount> threads;
....
};
}}

ThreadPool<n> pool;行抛出错误并且只接受const值。是否有任何方法可以将n值传递给ThreadCount?

EDIT:我希望线程的大小在编译后可以改变。

在编译时必须知道模板参数和std::array的大小,以便编译器能够生成正确的代码。

选项:

所有内容的静态大小。一切都是在编译时设置的,不能在运行时更改。constexpr .文档

#include <array>
#include <thread>
template <unsigned ThreadCount>
class ThreadPool {
    std::array<std::thread, ThreadCount> threads;
};
int main()
{
    constexpr unsigned n = 10; // n is fixed at compile time and unchangable.
    ThreadPool<n> pool;  //Error
}

std::vector, threadpool构造函数的参数,以及成员初始化列表

#include <vector>
#include <thread>
class ThreadPool {
    std::vector<std::thread> threads;
public:
    ThreadPool(unsigned n): threads(n) // constructs threads with n elements
    {
    }
};
int main()
{
    unsigned n = 10;
    ThreadPool pool(n);
}

不,在您的情况下您不能将n传递给它。在c++中,模板是静态编译的。所以它的参数必须是编译时常数。所以constexpr unsigned n = 10;将使编译器高兴,但我不希望你想要的。

但是如果你使用C99,它有一个称为可变长度数组的特性(在C11中它成为可选的),允许你声明一个具有运行时大小的数组