Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr function not calculate value in compile time

I want to compare meta programming and use of constexpr in c++0x. then I write a fib function in both model. when I use meta programming model, answer print out very fast because it calculated in compile time. but when I use constexpr funcion it calculate value in run time, not in compile time. I using g++( gcc ) 4.8 .can any body help me?

#include <iostream>
using namespace std;
#define NUM 42

template <unsigned int N>
struct Fibonacci {
    enum { value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value };
};

template <>
struct Fibonacci<1> {
    enum { value = 1 };
};

template <>
struct Fibonacci<0> {
    enum { value = 1 };
};

constexpr unsigned int fib(unsigned int n)
{
    return (n > 1 ? fib(n-1) + fib(n-2) : 1 );
}

int main()
{

    cout << "Meta_fib(NUM)      : " << Fibonacci<NUM>::value << endl; // compile time :)
    cout << "Constexpr_fib(NUM) : " << fib(NUM) << endl;        // run time :-?
    return 0;
}
like image 855
mostafa88 Avatar asked Dec 19 '13 13:12

mostafa88


2 Answers

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)};

like image 108
Sergei Nosov Avatar answered Sep 19 '22 20:09

Sergei Nosov


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.

like image 21
rici Avatar answered Sep 19 '22 20:09

rici