gpt4 book ai didi

c++ - constexpr 函数不在编译时计算值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:08:26 24 4
gpt4 key购买 nike

我想比较元编程和 constexpr 在 c++0x 中的使用。然后我在两个模型中都写了一个 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;
}

最佳答案

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

枚举 {i = fib(NUM)};

关于c++ - constexpr 函数不在编译时计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20682915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com