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
}
- What is this weird template that
takes<int N>? - What is this second
weird template<>? - What are the
enumerations 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?
Thanks!
In C++, template arguments can either be types (prefixed with
classortypename) or integers (prefixed withintorunsigned int). Here we are in the second case.template<> struct Factorial<0>is a complete specialization of Factorial class template, which means that0is considered a special value to which corresponds its own version of Factorial.enums are the way to compute values in metaprogramming C++
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>::valueis equivalent to simply writing “24” in your code.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.