Why constexpr is not the default for all function? [duplicate]

混江龙づ霸主 提交于 2021-01-26 20:34:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!