我想比较元编程和 c++0x 中 constexpr 的使用。然后我在两个模型中都写了一个 fib 函数。当我使用元编程模型时,答案打印出来非常快,因为它是在编译时计算的。但是当我使用 constexpr 函数时,它会在运行时计算值,而不是在编译时。我使用 g++( gcc ) 4.8 。任何人都可以帮助我吗?
#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;
}