Thursday, July 4, 2013

Nested C++ template specialization

C++ template specialization can be a rather advanced topic.
It's much used on meta-programming to provide optimizations.

It's better to avoid nesting what's already difficult.
Coping with complexity isn't necessarily the best solution.
Sorry if I disappoint you.

As an example of what I'm say, find below a quick example that will help optimize natural numbers exponentiation. It's slightly more elaborated than the one provided on C++ Templates: The Complete Guide by Nicolai Josuttis and Daveed Vandevoorde.

The first part is the "nested" meta-program:

template< unsigned long long B, unsigned char P >
struct exponentiation
{
    enum
    {
        result = B * exponentiation< B, P - 1 >::result
    };
};

template< unsigned long long B >
struct exponentiation< B, 0 >
{
    enum
    {
        result = 1ULL
    };
};

The second part is (perhaps) a convenience wrapping:

template< unsigned long long B >
struct base
{
    template< unsigned char P >
    struct power
    {
        enum { result = exponentiation< B, P >::result };
    };
};

The usage should be obvious:

char buffer[ base<2>::power<56>::result ];

The maximum compile-time capacity of Oracle Solaris Studio 12.3 for Solaris 11.1 running on Intel x64 is for computing the power of 2 to 61:

2305843009213693952