[英]Why GCC does not evaluate constexpr at compile time?
As an example: 举个例子:
class something {
public:
static constexpr int seconds(int hour, int min, int sec)
{ return hour*3600+min*60+sec; }
}
then: 然后:
printf("Look at the time: %d\n", something::seconds(10, 0, 0));
Will compile to a call to the function using g++, instead of putting a constant number. 将编译为使用g ++调用函数,而不是使用常数。 Why would g++ do that?
为什么g ++会这样做? There's no gain in it and kinda defeats the purpose of using constexpr instead of awful macros.
它没有任何好处,有点挫败了使用constexpr而不是糟糕的宏的目的。
Why would g++ do that?
为什么g ++会这样做?
constexpr
functions only must be evaluated at compile time in situations where the result is used as a constant expression. constexpr
功能仅必须在其中结果被用作常量表达式中的情况下编译时进行评估。 These include things like initializing a constexpr
variable and being used as a template argument. 这些包括初始化
constexpr
变量和用作模板参数。
In other situations, even when a constexpr
function is invoked with arguments that are all themselves constant expressions, it is up to the implementation to do what it wants. 在其他情况下,即使使用自身都是常量表达式的参数调用
constexpr
函数,也可以由实现来执行它想要的操作。 Typically, it'll depend on the optimization flags. 通常,它将取决于优化标志。 On both gcc 6.2 and clang 3.9.1, for instance,
-O0
will emit a call at runtime but -O1
will emit the constant 36000
. 例如,在gcc 6.2和clang 3.9.1上,
-O0
将在运行时发出调用,但-O1
将发出常量36000
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.