将数组数据插入模板
Insert array data into template
我想用数组中的一些整数填充模板,但这似乎在C++中是不允许的。举个例子:
我用整数定义了一个常量数组。
const int array[4] = {0, 1, 2, 3};
我的模板是这样的:
template<int T> TestClass ...
在下面,第一种方法没有问题,但第二种方法无法编译:
TestClass<12> ... // works
TestClass<array[0]> ... // does not work
编译器说运算符 '[' 不允许在 temlate 中使用。但是这是什么原因,我怎样才能优雅地解决这种情况?是否也可以使用 for
循环的计数器i
来选择数组的整数,例如:
TestClass<array[i]>
将数组转换为constexpr
变量:
constexpr int array[4] = {0, 1, 2, 3};
甚至更好:
constexpr std::array<int, 4> myArray{0, 1, 2, 3};
由于您的数组将被constexpr
,因此它的用法在编译时将有效。
请务必为 std::array
版本启用 c++14。
一个完整的类型模板参数,如类模板 TestClass 中的 int ...,应该是一个编译时常量,这就是这样的代码无法编译的原因。
相关文章:
- 在 QAbstractTableModel 上的 setModel 之后插入数据
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 增强循环缓冲区push_back在前面插入数据
- 程序 使用链表插入数据时停止工作
- 如何与LIBPQXX API同时插入数据?(PostgreSQL,线程)
- 如何在其中创建2D字符串向量并插入数据
- 二叉搜索树插入数据问题
- 通过指定第 n 个节点位置在单链接列表中插入数据
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 在std::映射中插入数据
- 插入数据时出现分段错误
- 如何在C++的排序文件中插入数据
- 在二进制树中插入数据时出错
- 在双通道矩阵中插入数据
- 用于插入数据而非搜索的最快数据结构
- 无法在映射的映射的STL映射中插入数据
- 如何插入数据到sqlite使用qt
- 为什么在c++中,在矢量结束后插入数据是错误的
- 在没有c++方法的类中插入数据
- 在矢量中插入数据时多次调用复制构造函数