문제

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;
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top