Since it is possible that a function declared as constexpr can be called at run time, by what criteria does the compiler decide whether to evaluate it at compile time or at run time?
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 am not aware at compile time, which is probably the reason that the compiler treats POW () as a regular function that is called at runtime. However, this dynamic, as far as it can be convenient, has some impractical consequences. For example, can there be a case where I would like the compiler to compute the constexpr function at compile time, when the compiler decides to treat it as a normal function, and also when it would work at compile time? Are there any known errors?
c ++ c ++ 11 runtime constexpr compile-time
CaffeineAddict Jan 09 '13 at 23:18 2013-01-09 23:18
source share