This code
#include <array>
void foo(const int length) {
std::array<int, length> arr; //line 4
}
int main(){
const int length = 10;
std::array<int,length> arr;
}
fails with the error message
: In function 'void foo(size_t)':
:4:27: error: 'length' is not a constant expression
std::array<int, length> arr;
https://gcc.godbolt.org/z/MMQXHx
The parameter length is marked as const.
Why is it not possible to pass the const length of a local std::array as a function parameter?
Why does it work in the main method?
I know, that a template approach like this would work
template <size_t length>
void foo() {
std::array<int, length> arr;
}
const does not mean "compile-time constant", or "constant expression".
It means "don't let me change the value of this runtime object".
Sometimes a const object can be considered constant "enough" for your needs, and the compiler will permit the code in those cases. A template argument is not one of those cases.
In main, use constexpr instead; it's a keyword that was added to the language for this purpose.
That's not going to help you with foo, though, in which you simply can't do what you're trying to do. The equivalent is to make foo a function template, with length being a template parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With