Why is std::declval not constexpr?

Viewed 352

As in question - why is code like this illegal in cpp?

static_assert(std::declval<std::array<int, 4>>().size() == 4);

Is it an overlook in standard or there is some deeper rationale why std::declval is not constexpr?

1 Answers

This line:

static_assert(std::declval<std::array<int, 4>>().size() == 4);

fails to compile, because you are using declval in an evaluated context. This is not allowed, and if you do that your program is ill-formed. declval can only be called in unevaluated contexts such as in a decltype or sizeof.

Making a function constexpr means that it can be called at either run-time, or compile-time. Since declval simply can't be called, there's no point making it constexpr. I suppose there wouldn't be any harm in making it constexpr, but either way, it doesn't matter.

Related