将数组数据插入模板

Insert array data into template

本文关键字:插入 数据 数组      更新时间:2023-10-16

我想用数组中的一些整数填充模板,但这似乎在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 ...,应该是一个编译时常量,这就是这样的代码无法编译的原因。