在 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;
}
上面的程序在编译时计算阶乘值。我想在编译时而不是在运行时使用 cout 打印阶乘值。我们如何才能在编译时打印阶乘值?
我用的是VS2009。
谢谢!
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?
I am using VS2009.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
阶乘可以在编译器生成的消息中打印为:
错误消息:
这里
3628800
是10
的阶乘。在 ideone 上查看:http://ideone.com/094SJz
那么您在寻找这个吗?
编辑:
Matthieu 要求一个聪明的技巧来打印阶乘并让编译继续。这是一种尝试。它不会给出任何错误,因此编译成功并出现一个警告。
编译时会出现以下警告:
这里
120
是5
的阶乘。ideone 演示:http://coliru.stacked-crooked.com/a/c4d703a670060545
您可以编写一个漂亮的宏,然后将其用作:
看起来很棒。
The factorial can be printed in compiler-generated message as:
Error message:
Here
3628800
is factorial of10
.See it at ideone : http://ideone.com/094SJz
So are you looking for this?
EDIT:
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.
It gets compiled with this warning:
Here
120
is factorial of5
.Demo at ideone : http://coliru.stacked-crooked.com/a/c4d703a670060545
You could just write a nice macro, and use it instead as:
That looks great.
在这种情况下,您真正想要的是静态断言:
如果您的编译器尚不支持
static_assert
,您可以使用BOOST_STATIC_ASSERT
。In that case, what you really want is a static assertion:
If your compiler does not support
static_assert
yet, you can useBOOST_STATIC_ASSERT
.我确信现在已经太晚了,但仍然如此。
I am sure it is far too late, but still.
肯定没有标准的方法。我也想不出特定于编译器的方法。
[[填充]]
There is definitely no standard way. I can't think of a compiler-specific way, either.
[[Filler]]