Here is an example of metaprogramming in C++:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
void fact()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}template metaprogramming
最新推荐文章于 2025-04-24 20:24:33 发布
本文展示了一个使用C++模板元编程实现阶乘的例子。通过递归模板特化的方式,无需运行时计算即可得到任意非负整数的阶乘值。
800

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



