Is there a way (possibly standard) to know inside
foo(const int s)if the function is executed at compile time or at runtime?
The standard ways to detect const if a constexpr function is evaluated at compile time at C++20/C++23:
if consteval (C++23)std::is_constant_evaluated (C++20, requires <type_traits>)There are non-standard ways under C++14/C++17:
__builtin_is_constant_evaluated of GCC/Clang (and surprisingly MSVC)std::_Is_constant_evaluated of MSVC (any C++ standard here)There isn't any standard way in pre-C++20 through.
Test script:
#if __cplusplus >= 202002L || _MSVC_LANG>= 202002L
#include <type_traits>
#endif
bool is_constant_evaluated() {
#if __cpp_if_consteval >= 202106L
if consteval { return true; }
// both MSVC (non-comformant __cplusplus) and by-default _MSVC_LANG and other compiles with conformant __cplusplus
#elif __cplusplus >= 202002L || _MSVC_LANG>= 202002L
if (std::is_constant_evaluated()) return true;
#elif defined(__GNUC__) // defined for both GCC and clang
if (__builtin_is_constant_evaluated()) return true;
#elif defined(_MSC_VER)
if (__builtin_is_constant_evaluated()) return true;
#else
#error "NAWH we don't think we can detect compile time in this compiler";
#endif
return false;
}
int main() {
return is_constant_evaluated();
}
And it compiles and works properly even if it's MSVC and C++17/C++14. (assembly here)