【发布时间】:2017-12-02 06:37:07
【问题描述】:
我正在学习constexpr,据我所知,constexpr 告诉编译器在编译时而不是运行时计算函数。我使用以下代码进行测试,但遇到了一个我真的不明白的错误。你能解释一下为什么吗?
#include <iostream>
#include <array>
using namespace std;
constexpr int foo(int i)
{
return i + 5;
}
int main()
{
int i = 10;
std::array<int, foo(5)> arr; // OK
// But...
std::array<int, foo(i)> arr1; // Error
}
错误是:'i' 的值在常量表达式中不可用。为什么? i 是事先声明的,为什么它必须是 const?
【问题讨论】:
标签: c++ c++11 metaprogramming constexpr stdarray