我可以用constexpr函数声明一个静态数组

mew*_*234 2 c++ constexpr c++11

// since we can dedfine a static array like this
int a[5] = {0};
// decltype(a[5]) is `int [5]`

// Then how about this way?
constexpr int sum(int a, int b) { return a + b; }
int a, b;
std::cin >> a >> b;
int arr[sum(a, b)] = {0};
Run Code Online (Sandbox Code Playgroud)

它可以成功编译,但是是arr一个静态数组?当我尝试arrtypeid().name()或打印类型时boost::typeindex::type_id_with_cvr,我得到以下错误:

error: cannot create type information for type 'int [(<anonymous> + 1)]' because it involves types of variable size
 std::cout << typeid(decltype(arr)).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)

Ala*_*les 6

由于编译时的值ab未知,因此结果sum不是constexpr.

代码编译可能是因为你正在使用GCC,它有一个扩展,允许在堆栈上声明可变大小的数组,标准c ++不允许这样做.