After relaxing the rules for the constexpr it seems as these functions can be used everywhere. They can be called on both constant (constexpr) and local (mutable) variables as well. So for me it seem as just a hint for the compiler (like inline). I just keep writing it everywhere and remove it if compiler complains. So compiler seems to know everything if a function can be evaluated at compile time or not. Why is it not the default behavior and why do i have to mark anything as constexpr ?
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.
constexpr is a compile time feature, where inline/static are runtime features. The meaning of constexpr is more restricted than static. The meaning is that given a particular input value the return value is always the same, and the copiler ought to be able to work it out completely during compilation.
constexpr
is an interface guarantee. It means that you can use the function in constant expressions.
Once people can use them in constant expressions, they will. But what if you didn't mean for your function to be used that way? What if you previously had a simple implementation that happened to be constexpr-possible, but in a later revision you need to change that (e.g. because you now need to add log output)?
If you remove the constexpr marker, the usage in constant expressions stops compiling, when it worked before, and the users of your function will be upset. Better to not make the function constexpr in the first place, allowing you more freedom to change it later.
But if the compiler automatically makes your function constexpr, you don't have that choice.
As pointed here, it makes difference to use function template specialization, defined with constexpr
specifier or not in (e.g.) SFINAE context:
The addition of constexpr is causing function templates to be instantiated in unevaluated contexts that otherwise would not.
So, sometimes it would be an undesired behaviour to have all the functions implicitly defined as constexpr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With