问题
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 ?
回答1:
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.
回答2:
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
.
来源:https://stackoverflow.com/questions/35309115/why-constexpr-is-not-the-default-for-all-function