c++: constexpr function doesn't evaluate at compile time when using with std::cout

As I realize constexpr functions are evaluated at compile time

Not really. They can be evaluated at compile-time, but they are not guaranteed to do so, unless they're invoked in a context where a constant expression is required.

One such context is the declaration of a constexpr variable.


constexpr means "can be evaluated at compile time" rather than "must be evaluated at compile time". If you want to see it evaluated at compile time you can call it in a context that requires to be evaluated at compile time, for example a template parameter:

std::array<int, sum(3,5)> x;

Note that the motivation for constexpr is the other way around than many would expect. constexpr tells the compiler that you can use it eg as template parameter and if sum was not constexpr you'd get a compiler error. It is not to make sure that the function always is evaluated at compile time.

Tags:

C++

C++14