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
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?
Thanks!
See Question&Answers more detail:os