在编译时计算小整数的阶乘 [英] Computing the factorial of a small integer at compile time
问题描述
我刚刚(再次)实现了一个递归模板,用于在编译时计算整数的阶乘(谁曾以为有一天我实际上会需要它!).尽管如此,我还是没有自己动手,而是去 Boost 寻找答案.但是,特殊数学中的阶乘函数特别禁止将其与整数类型一起使用,因此我只是编写了自己的函数.
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中我应该使用另一个功能吗?我应该将整数转换为double
并使用boost::factorial
函数吗?计算是否在编译时执行?
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?
推荐答案
您不需要Boost,如果您拥有C ++ 11,这只是1-liner:
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< 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屋!