How can my code do one thing at compile-time, but another thing at run-time?

我是研究僧i 提交于 2020-11-28 07:58:05

问题


I'm implementing a constexpr int foo(); function. In the body of foo(), I want to do something different (and possibly return something different) at compile time and something different at run-time.

With C++20, I can use std::is_constant_evaluated:

constexpr int foo() { return std::is_constant_evaluated() ? 123 : 456 };

but what if I'm using C++17 (or earlier) - what can I do with the same effect?

Note: Compiler-specific solutions are acceptable (though less desirable).


回答1:


Note: Compiler-specific solutions are acceptable (though less desirable).

Let's mention the most obvious ones:

gcc has __builtin_is_constant_evaluated() at least documented since 9.2.0.

clang has the same builtin since clang-9.



来源:https://stackoverflow.com/questions/64970832/how-can-my-code-do-one-thing-at-compile-time-but-another-thing-at-run-time

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