如何将无符号参数传递给模板
How to pass an unsigned argument to a template?
我有两个文件-其中一个是我传递给模板的无符号参数,另一个包含模板声明和定义。
/*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中它成为可选的),允许你声明一个具有运行时大小的数组
相关文章:
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 通过参数传递 lambda(无函数类型模板)
- C++如何将变量传递给带有无符号 int & 的参数uint16_t函数?
- 是否可以确定函数的参数是否已签名或无符号,以实现可能性超载函数
- 模板参数可以既是 int 又可以是无符号长整型吗?
- 将迭代器作为参数传递时无匹配的函数调用
- 在与时间一起使用 srand 时,如果我没有time_t参数明确地将参数转换为无符号的 int 参数,这有关系吗?
- Variadic模板参数包只接受无符号int或size_t作为其类型
- 如何获得无符号的int作为控制台参数
- 使用 Boost.Python 使用无符号字符和参数公开方法
- 为什么丢弃的参数类型是无符号长长
- 将无符号 int 的指针传递到长 int 的指针
- 推导出非类型模板参数无符号 int/size_t
- Ada到C++:传递一个无符号的64位值
- 当将负文字作为无符号参数传递时,可以g++警告
- C++:比较可变参数无符号 int 模板参数的帮助程序
- 禁止使用boost::p rogram_options对无符号值进行负参数
- 在C++中通过引用传递无符号字符数组
- 如何将无符号参数传递给模板
- Rgd:如何传递无符号字符