在C ++中在编译时计算和打印阶乘 [英] Calculating and printing factorial at compile time in C++
问题描述
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;
}
<我想在编译时打印factorial值,而不是在运行时使用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。
谢谢! / 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> _ '具有不完整的类型,无法定义
::值> _ ;
^
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 int
factorial = 120]':main。 cpp:16:39:从这里需要
main.cpp:13:48:warning:在隐式常量转换中溢出
[-Woverflow] struct _ {operator char(){return factorial }};
//总是溢出
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
code> 5 。
Here 120
is factorial of 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 ++中在编译时计算和打印阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!