使用模板元编程来计算阶乘 [英] calculating factorial using template meta-programming
问题描述
我不明白这部分代码(来自维基百科)的工作原理:
I do not understand how this piece of code (from Wikipedia) works:
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
- 模板
需要< int N>
? - 这是第二个
模板<>
? -
枚举
-
的优势是什么,而不是正常的
运行时因子计算? - 你们多久使用一次?我一直在使用C ++一段时间,但从来没有使用过这个。
- What is this weird template that
takes
<int N>
? - What is this second
weird template
<>
? - What are the
enum
erations for? - What is the advantage of using this rather than normal runtime factorial calculation?
- How often do you people use this? I have been using C++ for a while now, but never used this before. How big a part of C++ was I missing out on?
- 这个奇怪的模板是什么?
< int N>
? - What is this weird template that takes
<int N>
? - 这是第二个奇怪的
模板;>
? - What is this second weird
template <>
? - 枚举是什么?
- 使用这个而不是正常的运行时因子计算的优点是什么?
- 你多久使用一次?我一直在使用C ++,但从来没有使用过这个
谢谢!
推荐答案
在C ++中,模板参数可以是类型(前缀为 class
或 typename
)或整数(前缀为 int
或 unsigned int
)。这是第二种情况。
In C++, template arguments can either be types (prefixed with class
or typename
) or integers (prefixed with int
or unsigned int
). Here we are in the second case.
> struct Factorial< 0>
是Factorial类模板的完全专业化,这意味着 0
被认为是一个特殊值,
template<> struct Factorial<0>
is a complete specialization of Factorial class template, which means that 0
is considered a special value to which corresponds its own version of Factorial.
枚举是在元编程中计算值的方法C ++
enums are the way to compute values in metaprogramming C++
首先创建此代码的原因是创建一个概念证明,可以使用元编程完成演算。其优点是生成的代码非常高效(调用 Factorial< 4> :: value
等效于在代码中简单写入24。
The reason why this code was created in the first place is to create a proof of concept that calculus can be done using metaprogramming. The advantage is that generated code is extremely efficient (calling Factorial<4>::value
is equivalent to simply writing "24" in your code.
这种功能很少使用此方法实现,但是元编程现在越来越多地使用。请参见 Boost元编程库以获取一个可以做什么的提示。
Such functionality is rarely achieved using this method, but metaprogramming is used more and more nowadays. See Boost meta-programming library to get a hint of what can be done.
这篇关于使用模板元编程来计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!