提升:计算小整数在编译时的阶乘 [英] Boost: computing the factorial of a small integer at compile time

查看:141
本文介绍了提升:计算小整数在编译时的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚实施(再次)在编译时计算一个整数的阶乘递归模板(谁曾想过有一天我会真的需要它!)。尽管如此,而不是我自己的滚动,我去提振寻找一个答案。然而,在特殊的数学阶乘函数明确禁止其使用​​整数类型,所以我只是写我自己的。

I just implemented (once again) a recursive template for computing the factorial of an integer at compile time (who would had thought that some day I'll actually need it!). Still, instead of rolling my own, I went to boost looking for an answer. However, the factorial function in special math specifically forbids its use with integer types, so I just wrote my own.

不过,有升压另一个函数,我应该使用?我应该投我整一倍,并使用了boost ::阶乘函数?被计算在编译时进行的?

Still, is there another function in boost that I should use? Should I cast my integer to double and use the boost::factorial function? Is the computation performed at compile time?

推荐答案

您无需升压,这仅仅是1班轮,如果你有C ++ 11:

You don't need Boost, this is just 1-liner if you have C++11:

constexpr uint64_t factorial(uint64_t n) { 
    return n == 0 ? 1  :  n * factorial(n-1); 
}

和它的工作,即使你的arg是不是编译时间常数也。 uint64_t中将以N'LT工作; 21.

And it will work even if your arg is not compile time constant too. uint64_t will work with n < 21.

如果你正在做它在编译时间和浮点值乘 - 也就没有转换开销(转换将在编译的时候也是如此)。

If you are doing it in compile time and multiply with floating point value - there will be no conversion overhead (conversion will be at compile time too).

这篇关于提升:计算小整数在编译时的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆