constexpr函数无法在编译时计算值 [英] constexpr function not calculate value in compile time

查看:129
本文介绍了constexpr函数无法在编译时计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较元编程和c ++ 0x中constexpr的使用。
然后我在两个模型中都编写了一个fib函数。
当我使用元编程模型时,因为它是在编译时计算出来的,所以答案打印很快。但是当我使用constexpr函数时,它将在运行时而不是在编译时计算值。
我使用g ++(gcc)4.8。有人能帮助我吗?

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


推荐答案

我相信原因是 constexpr 不能保证在编译时执行。要强制执行编译时评估,您必须将其分配给编译时别名。例如,

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,

枚举{i = fib(NUM)};

这篇关于constexpr函数无法在编译时计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆