views:

39

answers:

1

I have a template class that has a template member function that needs to be specialized, as in:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};

Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit specialization in non-namespace scope 'class X<T>'

I tried:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}
};

template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}

But this causes both VC and GCC to complain.

What's the right way to do this?

+2  A: 

Very common problem. One way to solve it is through overloading

template <typename T>
struct type2type { typedef T type; };

template <typename T>
class X
{
public:
    template <typename U>
    void Y() { Y(type2type<U>()); }

private:
    template<typename U>
    void Y(type2type<U>) { }

    void Y(type2type<int>) { }
};
Johannes Schaub - litb
Thanks. Unfortunately my template argument is actually an integer (as in `template <int N>`), didn't think it'd make a difference. Any ideas?
uj2
just replace `typename T` and `U` with `int N` and you are served fine :) This will work just like the type way.
Johannes Schaub - litb