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模板网!