- What is this weird template that takes
<int N>
?
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.
- What is this second weird
template <>
?
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.
enums are the way to compute values in metaprogramming C++
- What is the advantage of using this rather than normal runtime factorial calculation?
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.
- 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?
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…