François Beaune François Beaune - 1 month ago 8
C++ Question

How to overload template class method for another template type?

What is the standard method in C++03, without using Boost, to either:


  1. Overload a template class method where the template type only appears in the return value of the method, or

  2. Specialize a template class method for another templated type.



In other words, how can this be made to work:

template <typename T, int N> struct Vector { T x[N]; };

struct Sampler
{
template <typename T>
T next() {
// Do some work and return a value of type T.
return T();
}

template <typename T, int N>
Vector<T, N> next() {
// Do some different work and return a value of type Vector<T, N>.
return Vector<T, N>();
}
};

int main() {
Sampler sampler;
sampler.next<double>();
sampler.next<Vector<float, 2> >();
return 0;
}


As written, both uses of
next()
call the first method, while I'd like the second use to call the second method.

Answer

Looks like you're asking for partial specialization of template functions. That's not in the language, but you can emulate it with tag dispatching or class templates. Here's an example with tag dispatch:

template <typename T> struct tag{};
struct Sampler
{    
    template <typename T>
    T next() {
        return next(tag<T>());   
    }

private:
    template <typename T>
    T next(tag<T>) {
        return T();
    }

    template <typename T, int N>
    Vector<T, N> next(tag<Vector<T,N> >) {
        return Vector<T, N>();
    }
};

Then you use it like this:

sampler.next<double>();
sampler.next<Vector<double,2> >();

Live demo

Note that you need a space between the last > > tokens in the second line before C++11.