c++ - 变量模板编译时数组

标签 c++ templates c++14 variadic-templates template-meta-programming

我目前正在学习 C++ 中的模板元编程,无意中发现了变量模板。作为一个有趣的练习,我决定使用以下用法来实现编译时静态数组 -

my_array<1,2,3,4> arr;  // gives an array with 4 members = 1,2,3,4

我已经尝试了几次迭代,一路上消除了语法错误,但现在我被卡住了,因为没有编译器给出有用的警告。这是我当前的代码 -

#include <iostream>

template<size_t... Enteries>
constexpr size_t my_array[sizeof...(Enteries)] = {Enteries...};

int main() {
    my_array<1,2,3,4,5,6> arr;
}

但目前它给出了 clang 的以下错误 -

static_array.cpp:7:10: error: expected ';' after expression
        my_array<1,2,3,4,5,6> arr;
                ^
                ;
static_array.cpp:7:24: error: use of undeclared identifier 'arr'
        my_array<1,2,3,4,5,6> arr;
                              ^
static_array.cpp:7:2: warning: expression result unused [-Wunused-value]
        my_array<1,2,3,4,5,6> arr;
        ^~~~~~~~~~~~~~~~~~~~~
1 warning and 2 errors generated.

和 gcc -

static_array.cpp: In function ‘int main()’:
static_array.cpp:7:24: error: expected ‘;’ before ‘arr’
  my_array<1,2,3,4,5,6> arr;
                        ^~~
static_array.cpp:7:27: warning: statement has no effect [-Wunused-value]
  my_array<1,2,3,4,5,6> arr;

我应该如何继续实现这个东西(最好使用变量模板,因为我知道这可以用旧的结构技术实现)。

最佳答案

如问题评论中所述,my_array<1,2,3,4,5,6>不是一种类型。 my_array是一个变量模板,它有一个你可以在专门化后使用的类型,但它不是一个类型,你不能按你现在的方式使用它。
您不能声明类型为 my_array<1,2,3,4> 的变量, 但您可以使用变量 my_array<1,2,3,4> . 举个例子,你想得到第N个元素吗? my_array<1,2,3,4,5,6>[N]; .

示例程序:

#include <iostream>

template<size_t... Enteries>
constexpr size_t my_array[sizeof...(Enteries)] = {Enteries...};

int main() {
   std::cout << my_array<1,2,3,4,5,6>[0] << std::endl;
}

输出:

1

关于c++ - 变量模板编译时数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44713110/

相关文章:

c++ - SFINAE 优雅地检查 "template template class"(在模板参数中)

c++ - 来自二维数组的特征图

c++ - 如何在 DirectX 中标准化模型大小?

c++ - 使用多个命名空间对 vtable 的 undefined reference

多个目标文件中的 C++ 模板和编译

c++ - CRTP 避免虚拟成员函数开销

c++ - 使用整数值作为模板参数的函数模板中的参数推导

c++ - 如何修改 Lambda 表达式以将输出放入文本文件?

c++ - 按值返回 boost ublas 矩阵仅在 vs2012 的发布配置中工作

c++ - Qt:优化绘画事件