(Realted to this other question of mine; if you give a look at that too, I would really appreciate it.)
If std::array<T,N>::size
is constexpr
, then why does the following code not even compile?
#include <array>
#include <iostream>
constexpr auto print_size = [](auto const& array){
constexpr auto size = array.size();
std::cout << size << '
';
};
int main() {
print_size(std::array<int,3>{{1,2,3}});
}
The error is the following:
$ g++ -std=c++17 deleteme.cpp && ./a.out
deleteme.cpp: In instantiation of ‘<lambda(const auto:1&)> [with auto:1 = std::array<int, 3>]’:
deleteme.cpp:10:42: required from here
deleteme.cpp:5:20: error: ‘array’ is not a constant expression
5 | constexpr auto size = array.size();
| ^~~~
But I wonder why.
At the lambda call site, the argument is known at compile time, and the lambda should be instantiated with auto
equal to std::array<int,3>
, where 3
is a compile time value, and so should be output of array.size()
.
What is wrong in my reasoning?
By the way, the same holds if I use a templated function instead of the generic lambda.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…