Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specializing a template member function of a template class?

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?

like image 743
uj2 Avatar asked Jun 14 '10 19:06

uj2


1 Answers

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>) { }
};
like image 78
Johannes Schaub - litb Avatar answered Nov 15 '22 10:11

Johannes Schaub - litb