#include <iostream>
template <int N>
struct fact {
enum { value = N * fact<N - 1>::value };
};
template <>
struct fact<1> {
enum { value = 1 };
};
int main()
{
std::cout << "5! = " << fact<5>::value << std::endl;
}
template <int N>
struct fact {
enum { value = N * fact<N - 1>::value };
};
template <>
struct fact<1> {
enum { value = 1 };
};
int main()
{
std::cout << "5! = " << fact<5>::value << std::endl;
}
本文介绍了一种使用C++模板元编程来实现计算整数阶乘的方法。通过递归模板特化的方式,展示了如何不使用运行时计算就能得到固定大小整数的阶乘值。这种方法在编译阶段完成计算,可以有效提高程序运行效率。
5116

被折叠的 条评论
为什么被折叠?



