I am learning constexpr
and, for my understanding, constexpr
tells the compiler to calculate functions during compile time instead of running time. I used the following code for testing but bumped into an error I really don't understand. Can you please explain why?
#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
}
The error is: the value of 'i
' is not usable in a constant expression. Why? i
is declared beforehand why does it have to be a const
?
Aucun commentaire:
Enregistrer un commentaire