H.Hatch
H.Hatch

Reputation: 3

Initialize std::array without constexpr

void test(const std::size_t& x) {
    std::array<std::string, x> arr;
}

When I compile the above code I get this error.

main.cpp: In function ‘void test(std::size_t&)’: main.cpp:15:24: error: ‘x’ is not a constant expression

How can I get the above code to compile?

Upvotes: 0

Views: 151

Answers (1)

johnmastroberti
johnmastroberti

Reputation: 847

Template arguments must always be constant expressions, and function parameters are never constant expressions. To make this code work, you could do as is suggested in the comments and use std::vector instead, or you could make your test function be a template and make x be a template parameter instead of a function parameter.

Upvotes: 3

Related Questions