[英]C++: constexpr fibonacci sequence evaluation
我正在研究 constexpr 並嘗試在 Stroustrup C++ 4th Ed 中實現一個示例。 第 312 頁。我的理解是fib(45)
的計算應該在編譯時完成,但是我的結果表明計算是在運行時進行的。
有誰知道我在使用constexpr
在編譯時建立fib(45)
的計算時哪里出錯了?
感謝您的指導。
#include <iostream>
using namespace std;
constexpr int fib_(int n)
{
return (n < 2) ? 1 : fib_(n - 1) + fib_(n - 2);
}
constexpr int ftbl[] { 1, 2, 3, 5, 8, 13 };
constexpr int fib(size_t n)
{
return (n < sizeof(ftbl)/sizeof(*ftbl)) ? ftbl[n] : fib_(n); }
int main(int argc, char *argv[])
{
cout << fib(45) << endl;
return 0;
}
根據建議更新代碼:
#include <iostream>
using namespace std;
unsigned int fibr(unsigned int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibr(n - 1) + fibr(n - 2);
}
constexpr unsigned int ftbl[] { 0, 1, 1, 2, 3, 5, 8, 13 };
constexpr unsigned int fib(size_t n)
{
return (n < sizeof(ftbl)/sizeof(*ftbl)) ? ftbl[n] : fib(n-2) + fib(n-1);
}
int main(int argc, char *argv[])
{
if (argc == 2) {
if (string(argv[1]) == "r") {
unsigned long x = fibr(44);
cout << x << endl;
}
} else {
constexpr unsigned long x = fib(44);
cout << x << endl;
}
return 0;
}
constexpr
表示可以在編譯時評估 function。
這個說法:
cout << fib(45) << endl;
不是需要對fib
進行編譯時評估的上下文,因此編譯器可能會或可能不會在運行時評估它。
您可以強制它在編譯時進行評估,如下所示:
constexpr auto res = fib(42);
cout << res << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.