gct
gct

Reputation: 14583

Specializing templated function for a templated type?

I've got a function:

// declaration of random, specialize this to provide random instances of types
template <typename T> T random() {
    static_assert(
        std::is_void<T>::value && false, "random() not implemented for type"
    );
}

I'd like to specialize it for another type, _point1d that's also templated:

template <typename T>
struct _point1d {
    _point1d(T x) : x(x) {}
    T x;
};

I tried this:

template <typename T>
_point1d<T> random<_point1d<T>>() { return _point1d<T>(random<T>()); }

But I get:

error: non-type partial specialization ‘random<_point1d<T> >’ is not allowed

With gcc. Is this possible?

Upvotes: 0

Views: 40

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477512

You cannot specialize function templates partially.

The standard solution is to use an intermediate helper class template:

template <typename> struct Aux;

template <typename U> struct Aux<_point1d<U>>
{
    static _point1d<U> f() { /* ... */ }
};

template <typename T> T random() { return Aux<T>::f(); }
//                                 ^^^^^^^^^^^^^^^^^^^

That way you only have one single function template, and all the details of selecting the right specialization are done inside the class template, which you can freely specialize partially or explicitly as you choose.

Upvotes: 3

Related Questions