为什么constexpr不是所有函数的默认值? [英] Why constexpr is not the default for all function?

查看:62
本文介绍了为什么constexpr不是所有函数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

放宽constexpr的规则后,似乎这些函数可以在任何地方使用.也可以在常量(constexpr)和局部(可变)变量上调用它们.因此对我来说,这似乎只是编译器的提示(如内联).我只是一直在各处编写它,如果编译器抱怨,请将其删除.因此,编译器似乎知道什么都可以在编译时求值.为什么不是默认行为,为什么我必须将任何内容标记为constexpr?

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 ?

推荐答案

constexpr 是接口保证.这意味着您可以在常量表达式中使用该函数.

constexpr is an interface guarantee. It means that you can use the function in constant expressions.

一旦人们可以在常量表达式中使用它们,他们就会使用.但是,如果您不打算那样使用函数该怎么办?如果您以前有一个可能实现constexpr的简单实现,但是在以后的版本中您需要更改它(例如,因为现在需要添加日志输出),该怎么办?

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)?

如果删除constexpr标记,则常量表达式中的用法将停止编译,而以前它不能正常工作,因此函数的用户将不高兴.最好不要将函数constexpr放在第一位,以便您以后有更大的自由来更改它.

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.

但是,如果编译器自动使您的函数成为constexpr,那么您就别无选择.

But if the compiler automatically makes your function constexpr, you don't have that choice.

这篇关于为什么constexpr不是所有函数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆