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

Viewed 238

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 Answers

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.

Related