Why GCC does not evaluate constexpr at compile time?

杀马特。学长 韩版系。学妹 提交于 2019-12-19 08:21:32

问题


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. Why would g++ do that? There's no gain in it and kinda defeats the purpose of using constexpr instead of awful macros.


回答1:


Why would g++ do that?

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.

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.



来源:https://stackoverflow.com/questions/41862118/why-gcc-does-not-evaluate-constexpr-at-compile-time

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