为什么GCC在编译时不评估constexpr? [英] Why GCC does not evaluate constexpr at compile time?

查看:112
本文介绍了为什么GCC在编译时不评估constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

class something {
public:
  static constexpr int seconds(int hour, int min, int sec)
  { return hour*3600+min*60+sec; }
}

然后:

printf("Look at the time: %d\n", something::seconds(10, 0, 0));

将使用g ++编译为对该函数的调用,而不是放置一个常数。
为什么g ++会这样做?毫无用处,并且有点违反了使用constexpr而不是可怕的宏的目的。

Will compile to a call to the function using g++, instead of putting a constant number. Why would g++ do that? There's no gain in it and kinda defeats the purpose of using constexpr instead of awful macros.

推荐答案


g ++为什么要这样做?

Why would g++ do that?

constexpr 仅功能必须在将结果用作常量表达式的情况下在编译时求值。其中包括初始化 constexpr 变量并用作模板参数的事情。

constexpr functions only must be evaluated at compile time in situations where the result is used as a constant expression. These include things like initializing a constexpr variable and being used as a template argument.

在其他情况下,即使使用本身都是常量表达式的参数调用 constexpr 函数,由实施来完成它想要做的事情。通常,它取决于优化标记。例如,在gcc 6.2和clang 3.9.1上, -O0 将在运行时发出调用,而 -O1 将发出常量 36000

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. 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在编译时不评估constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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