问题描述
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;
}
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。
谢谢! / p>
Thanks!
推荐答案
阶乘可以在编译器生成的消息中打印:
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:错误:aggregate' _ '具有不完整的类型,无法定义
::值> _ ;
^
这里 3628800
是 10
。
在ideone查看:
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;
}
使用此警告编译:
这里 120
code> 5 。
Here 120
is factorial of 5
.
在ideone演示:
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 ++中在编译时计算和打印阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!