14

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;
1
  • 1
    It is not even clear if constexpr std::initializer_list<int> li = {..}; is valid in C++11; it will be in C++1y. Commented Nov 27, 2013 at 12:04

2 Answers 2

32
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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.