Since it is possible that a function declared as constexpr can be called during run-time, under which criteria does the compiler decide whether to compute it at compile-time or during runtime?
template<typename base_t, typename expo_t>
constexpr base_t POW(base_t base, expo_t expo)
{
return (expo != 0 )? base * POW(base, expo -1) : 1;
}
int main(int argc, char** argv)
{
int i = 0;
std::cin >> i;
std::cout << POW(i, 2) << std::endl;
return 0;
}
In this case, i is unknown at compile-time, which is probably the reason why the compiler treats POW() as a regular function which is called at runtime. This dynamic however, as convenient as it may appear to be, has some impractical implications. For instance, could there be a case where I would like the compiler to compute a constexpr function during compile-time, where the compiler decides to treat it as a normal function instead, when it would have worked during compile-time as well? Are there any known common pitfalls?
POW((unsigned __int64)2, 63)
. Would that still count as a constant expression? – Hornwortconstexpr
is only required to be evaluated when its result is used as a template parameter, array bound, or other integral constant. Any other time is an optimization. In fact, even when given constant expression arguments, it might be required to execute at runtime.constexpr int func(int p) { return !p ? 1 : throw std::exception("HI");}
must be evaluated at runtime when given a non-zero input. – Alexipharmicconstexpr int a = POW(5, 4);
. That's essentially computed at compile time. But you can of course still usePOW
in other places. – Hypermetropia