C++ Template Specialization with Constant Value

tadman picture tadman · Jan 30, 2011 · Viewed 65k times · Source

Is there a straightforward way for defining a partial specialization of a C++ template class given a numerical constant for one of the template parameters? I'm trying to create special constructors for only certain kinds of template combinations:

template <typename A, size_t B> class Example
{
    public:
        Example() { };

        A value[B];
};

template <typename A, 2> class Example
{
    public:
        Example(b1, b2) { value[0] = b1; value[1] = b2; };
};

This example won't compile, returning an error Expected identifier before numeric constant in the second definition.

I've had a look through a number of examples here and elsewhere, but most seem to revolve around specializing with a type and not with a constant.

Edit:

Looking for a way to write a conditionally used constructor, something functionally like this:

template <typename A, size_t B> class Example
{
    public:
        // Default constructor
        Example() { };

        // Specialized constructor for two values
        Example<A,2>(A b1, A b2) { value[0] = b1; value[1] = b2; };

        A foo() {
          A r;

          for (size_t i = 0; i < b; ++b)
            r += value[i];

          return r;
        }

        // Hypothetical specialized implementation
        A foo<A, 2>() {
          return value[0] + value[1];
        }

        A value[B];
};

Answer

Foo Bah picture Foo Bah · Jan 30, 2011

You need to put the specialization in the correct place:

template <typename A> class Example<A,2>

If you want to create a subclass:

template <typename A> class ExampleSpecialization : public Example<A,2>

The behavior for specializing on typedefs is similar to the behavior for specializing on an integer parameter.