mos*_*a88 6 c++ compile-time template-meta-programming c++11 gcc4.8
我想比较元编程和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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3093 次 |
| 最近记录: |