0
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?

1
  • 4
    What is the reason that you try to use std::array instead of std::vector if the size is not a compile-time constant? That is pretty much the difference in use case between the two. Commented Apr 27, 2022 at 23:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

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.