编译时数组常量

std*_*ave 11 c++ standards templates compile-time-constant

我似乎错过了一些相当基本的东西.我正在尝试在编译时使用const数组成员.

const int list[3] = { 2, 5, 7 };
const int a = list[2]; // this doesn't error?

template<int N1, int N2>
struct tmax {
  enum { value = ((N1 > N2) ? N1 : N2) };
};

const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // error is here

int main()
{
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

prog.cpp:10:24: error: 'list' cannot appear in a constant-expression
prog.cpp:10:30: error: an array reference cannot appear in a constant-expression
Run Code Online (Sandbox Code Playgroud)

这是相关的IDEOne链接

那么为什么这不起作用呢?我错过了什么?我该怎么办?

bam*_*s53 9

仅仅因为一个对象const并不意味着它是一个编译时常量表达式.

main.cpp:10:20: error: non-type template argument is not a constant expression
const int c = tmax<list[0],list[1]>::value; // error is here
                   ^~~~~~~
main.cpp:10:20: note: read of non-constexpr variable 'list' is not allowed in a constant expression
main.cpp:1:11: note: declared here
const int list[3] = { 2, 5, 7 };
          ^
Run Code Online (Sandbox Code Playgroud)

这就是constexpr:

constexpr int list[3] = { 2, 5, 7 };

template<int N1, int N2>
struct tmax {
    enum { value = ((N1 > N2) ? N1 : N2) };
};

const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // works fine now
Run Code Online (Sandbox Code Playgroud)

至于为什么这样做:

const int a = list[2]; // this doesn't error?
Run Code Online (Sandbox Code Playgroud)

初始化const变量不需要常量表达式:

int foo(int n) {
    const int a = n; // initializing const var with a non-compile time constant
Run Code Online (Sandbox Code Playgroud)