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

can I declare a static array with constexpr function

// 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};

可以编译成功,但是arr是静态数组吗? 当我尝试使用 typeid().name()boost::typeindex::type_id_with_cvr 打印 arr 类型时,出现以下错误:

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;

由于 ab 的值在编译时未知,因此 sum 的结果不是一个 constexpr。

代码编译大概是因为您使用的 GCC 具有允许在堆栈上声明可变大小数组的扩展,标准 c++ 不允许这样做。