Gabriel
Gabriel

Reputation: 3107

How to specialize a template member function depending on the class' template arguments?

I would like to write this:

template<typename T1, typename T2>
class OK
{
    T1 t1;
    T2 t2;

public:
    template<typename TX> const TX & GetRef() const;
};

template<typename T1,typename T2>
template<>
const T1 & OK<T1,T2>::GetRef<T1>() const { return t1; }

template<typename T1,typename T2>
template<>
const T2 & OK<T1,T2>::GetRef<T2>() const { return t2; }

Which VS10 fails to compile.

To check my understanding of template specialization, I tried and compiled this all right:

typedef int  T1;
typedef char T2;
class OK
{
    T1 t1;
    T2 t2;

public:
    template<typename TX> const TX & GetRef() const;
};

template<>
const T1 & OK::GetRef<T1>() const { return t1; }

template<>
const T2 & OK::GetRef<T2>() const { return t2; }

What am I missing? Is what I want to do even possible?

Edit: I'd like to have getters for all fields, all called GetRef(), so the user can write something like:

OK<float,double> ok;
float a = ok.GetRef<float>();
double b = ok.GetRef<double>();

Upvotes: 4

Views: 109

Answers (1)

You cannot specialize a member template of a class template without specializing the template. That is, either you provide a full specialization on which T1 and T2 are fixed on the class template and then TX can also be fixed or you cannot fix TX.

The simple solution is not to specialize the template function, but rather provide a different overload:

template<typename T1, typename T2>
class OK
{
    T1 t1;
    T2 t2;
public:
    const T1& GetRef() const { return t1; }
    template<typename TX> const TX & GetRef() const;
};

Upvotes: 5

Related Questions