Adrian Costin
Adrian Costin

Reputation: 438

is constexpr const Type necessary in template in order for functions to return compile time const values?

looking at the implementation for std::array in c++ i see something i can't quite wrap my head around..

for example, the function that returns the first element in the array is defined as:

constexpr const-reference
front() const noexcept
{.......}

where const-reference is defined as const value_type&, so the whole expression above evaluates to constexpr const value_type&. knowing that in some situations we might want the value returned by the function to be known at compile time, my question is why are they using both constexpr and const on the same line? isn't the const redundant as it was already said that we are going to be returning a constexpr ?

Upvotes: 3

Views: 79

Answers (1)

max66
max66

Reputation: 66230

so the whole expression above evaluates to constexpr const value_type&

Not exactly: constexpr, for a function/method, mean that the function/method can be executed (also) compile time, not that the returned value is constexpr.

my question is why are they using both constexpr and const on the same line? isn't the const redundant as it was already said that we are going to be returning a constexpr ?

It was redundant in C++11.

constexpr was introduced in C++11 and, in C++11, a constexpr method was also (necessarily) a const method.

This changed starting from C++14 (a good explanation here)

So, starting from C++14, consexpr and const (for a method) are decoupled and, as you can see in cppreference, the std::array::front() non-const version is constexpr (starting from C++17).

Upvotes: 1

Related Questions