Template specialization

In the last post I define a recursive template function to calculate factorial. But since only the first 21 factorials fit in an unsigned 64-bit int I can just define them all with specialization.

// all overflow calculations return zero
template< int N > factorial( )  { return 0; /* overflow */ }

// brute force
template<> factorial< 0 >( )  { return 1; }
template<> factorial< 1 >( )  { return 1; }
template<> factorial< 2 >( )  { return 2; }
template<> factorial< 3 >( )  { return 3*2; }
template<> factorial< 4 >( )  { return 4*3*2; }
.. etc ..
template<> factorial< 20 >( )
{
    return 20ull *
        19 * 18 * 17 * 16 * 15 * 14 * 13 * 12 * 11 *
        10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
}

Factorial is probably the wrong example to use here, but this could be useful in other situations, such as defining specialized functions for all the values of an enum.

Comments

Leave a Reply