Reputation: 153
The following does not compile unless I put constexpr before initializer_list:
constexpr std::initializer_list<int> il = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::array<int, il.size()> a;
But initializer_list size is constexpr:
constexpr size_type size() const;
Upvotes: 14
Views: 1510
Reputation: 1270
By writing std::array<int, il.size()> a;
you are claiming that il.size()
can be evaluated at compile time with a constant result, allowing template instantiation.
That's why both the initializer_list::size()
method and your il
variable need to be declared as constexpr
.
Upvotes: 2
Reputation: 39121
std::initializer_list<int> il = rand() ? std::initializer_list<int>{1}
: std::initializer_list<int>{1,2,3};
std::array<int, il.size()> a;
That's why.
A constexpr
member function is a function that can be executed within a constant expression, it doesn't necessarily yield a result that is a compile-time constant. For example:
struct S
{
int m;
constexpr int foo() const { return m; }
};
S s{rand()};
int j = s.foo(); // only known at run-time
constexpr S cs{42};
int arr[cs.foo()]; // compile-time constant
Upvotes: 32