简体   繁体   English

为什么GCC在编译时不评估constexpr?

[英]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.

相关问题 constexpr-“在编译时评估值”到底是什么意思? - constexpr - What does “Evaluate value at compile time” mean exactly? 为什么gcc5.4不编译调用非constexpr函数的constexpr函数,而icpc编译呢? - Why gcc5.4 doesn't compile a constexpr function calling a non-constexpr function, but icpc does? constexpr函数中的GCC constexpr lambda和编译时评估 - GCC constexpr lambdas in constexpr functions and evaluation in compile time 为什么当我用constexpr执行代码时,有时在编译时求值,有时在运行时求值? - Why when I execute my code with constexpr, sometime it evaluate at the compile time and sometime at the runtime? 为什么 gcc/clang 认为返回的 constexpr object 不是 constexpr? - Why does gcc/clang think that a returned constexpr object is not constexpr? consitexpr构造函数在GCC编译时进行评估时给出不同的结果 - constexpr constructor gives a different result when evaluated at compile time by GCC gcc 如何在 constexpr 上下文中编译 C 函数? - How does gcc compile C functions in a constexpr context? 在编译时,Clang不会为非constexpr变量计算constexpr函数的值 - Clang doesn't evaluate the value of the constexpr function for the non-constexpr variable at compile time 为什么递归constexpr模板值不能编译? - Why recursive constexpr template value does not compile? 这些宏在编译时是否使用gcc对相同的代码求值? - Do these macros evaluate to the same code using gcc at compile-time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM