【发布时间】:2017-06-23 04:33:13
【问题描述】:
我目前正在学习 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>是数组。
标签: c++ templates c++14 variadic-templates template-meta-programming