constexpr function not calculate value in compile time

旧街凉风 提交于 2019-12-05 06:39:18

I believe the reason is that constexpr is not guaranteed to execute at compile-time. To enforce compile-time evaluation, you have to assign it to a compile-time alias. Like,

enum {i = fib(NUM)};

With gcc, at least, you can get the constexpr value to be computed at compile time by making it a static variable:

static const unsigned fibNUM = fib(NUM);

As I read the standard, it's still allowed to compute the value at startup, but in practice it will be computed at compile time.

A simple test to see if your constexpr are really being done at compile-time is to use an std::array:

#include <array>

std::array<int, Fibonacci<5>::value> arr;
std::array<int, fib(5)> arr2;

gcc has no complaints.

See this comment by Bjarne Stroustrup:

... according to the standard a constexpr function may be evaluated at compiler time or run time unless it is used as a constant expression, in which case it must be evaluated at compile-time. To guarantee compile-time evaluation, we must either use it where a constant expression is required (e.g., as an array bound or as a case label) or use it to initialize a constexpr. I would hope that no self-respecting compiler would miss the optimization opportunity to do what I originally said: "A constexpr function is evaluated at compile time if all its arguments are constant expressions."

constexpr is not guaranteed to be evaluated at compile time. This means, compiler can choose whether to evaluate at compile time or at run time. You can try to assign it to a compile time constant and check like this...

const long i = fib(NUM);// here i should be initialized at the time of 
                        // declaration
cout << "Meta_fib(NUM)      : " << Fibonacci<NUM>::value << endl; 
cout << "Constexpr_fib(NUM) : " << i << endl;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!