Here's a common question about constexpr
...
A suggestion: As of this writing the more correct and useful (and simpler) answer K-ballo's, which was not selected as best -- please upvote K-ballo and help approve the pending edit that improves it. Thanks.
When does a constexpr function get evaluated at compile time?
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?
Add a Comment
Comments are closed.