問題描述
template<unsigned int n>
struct Factorial {
enum { value = n * Factorial<n-1>::value};
};
template<>
struct Factorial<0> {
enum {value = 1};
};
int main() {
std::cout << Factorial<5>::value;
std::cout << Factorial<10>::value;
}
上面的程序在編譯時計算階乘值.我想在編譯時而不是在運行時使用 cout 打印階乘值.我們如何才能在編譯時打印階乘值?
above program computes factorial value during compile time. I want to print factorial value at compile time rather than at runtime using cout. How can we achive printing the factorial value at compile time?
我使用的是 VS2009.
I am using VS2009.
謝謝!
推薦答案
階乘可以在編譯器生成的消息中打印為:
The factorial can be printed in compiler-generated message as:
template<int x> struct _;
int main() {
_<Factorial<10>::value> __;
return 0;
}
錯誤信息:
prog.cpp:14:32: 錯誤:聚合 ‘_<3628800> __’ 類型不完整,無法定義_::值> __;^
prog.cpp:14:32: error: aggregate ‘_<3628800> __’ has incomplete type and cannot be defined _::value> __; ^
這里3628800
是10
的階乘.
在 ideone 上查看:http://ideone.com/094SJz
See it at ideone : http://ideone.com/094SJz
所以你在找這個嗎?
Matthieu 需要一個聰明的技巧來打印階乘并讓編譯繼續.這是一種嘗試.它沒有給出任何錯誤,因此編譯成功并發出一個警告.
Matthieu asked for a clever trick to both print the factorial AND let the compilation continue. Here is one attempt. It doesn't give any error, hence the compilation succeeds with one warning.
template<int factorial>
struct _{ operator char() { return factorial + 256; } }; //always overflow
int main() {
char(_<Factorial<5>::value>());
return 0;
}
編譯時帶有此警告:
main.cpp: 在實例化 '_::operator char() [with intfactorial = 120]': main.cpp:16:39: 從這里需要main.cpp:13:48: 警告:隱式常量轉換溢出[-Woverflow] struct _{ operator char() { return factorial + 256;} };//總是溢出
main.cpp: In instantiation of '_::operator char() [with int factorial = 120]': main.cpp:16:39: required from here main.cpp:13:48: warning: overflow in implicit constant conversion [-Woverflow] struct _{ operator char() { return factorial + 256; } }; //always overflow
這里120
是5
的階乘.
ideone 上的演示:http://coliru.stacked-crooked.com/a/c4d703a670060545
Demo at ideone : http://coliru.stacked-crooked.com/a/c4d703a670060545
你可以寫一個很好的宏,然后用它來代替:
You could just write a nice macro, and use it instead as:
#define PRINT_AS_WARNING(constant) char(_<constant>())
int main()
{
PRINT_AS_WARNING(Factorial<5>::value);
return 0;
}
那個看起來很棒.
這篇關于在 C++ 編譯時計算和打印階乘的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!