2
constexpr const_reference at( size_type pos ) const;

How can this overload of STL container accessors work with non-constexpr parameters? What are classical use cases of this overload?

0

2 Answers 2

9

There is no such thing as constexpr parameters in a function declaration. A constexpr function call can only be evaluated at compile time if and only if all parameters involved in that function call are constant expressions.

That being said, the only case where a constexpr function must be evaluated at compile time is when it is used to calculate a template parameter.

At least one use case for the example you give, is for std::array::at.

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

1 Comment

A really neat fearure is that the compiler is required to complain that the element is out of bounds if std::array<T,N>::at is evaluated in a constexpr context, as the throw that at does is not constexpr.
7

How can this overload of STL container accessors work with non-constexpr parameters?

Declaring a function constexpr means that if its called with constant expressions for all its arguments, then the result is also a constant expression.

It can still be called with non-constant arguments; you just can't use the result as a constant expression.

What are classical use cases of this overload?

Getting a compile-time constant out of a suitable container, for example:

constexpr std::array<int,5> values {{2,3,5,7,11}};

template <int n> void do_stuff();  // needs a compile-time constant
do_stuff<values.at(3)>();          // provide a compile-time constant

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.