'Explicit template specialization error

this one should be pretty easy. I'm playing with templates, but get a compiler error.

#include <iostream>

template <class T1, class T2>
class Pair
{
    private:
        T1 a;
        T2 b;
    public:
        T1& first();
        T2& second();
        Pair(const T1& aval, const T2& bval) : a(aval), b(bval) {}
};

template <class T1, class T2>
T1& Pair<T1,T2>::first()
{
    return a;
}


template <class T1, class T2>
T2& Pair<T1,T2>::second()
{
    return b;
}

// Explicit Specialization
template <>
class Pair<double, int>
{
    private:
        double a;
        int b;
    public:
        double& first();
        int& second();
        Pair(const double& aval, const int& bval) : a(aval), b(bval) {}
};

template <>
double& Pair<double,int>::first()
{
    return a;
}

template <>
int& Pair<double,int>::second()
{
    return b;
}


int main(int argc, char const *argv[])
{

    Pair<int, int> pair(5,6);
    //Pair<double,int> pairSpec(43.2, 5);
    return 0;
}

The error looks like this

main.cpp:42:27: error: no function template matches function template specialization 'first'
double& Pair<double,int>::first()
                          ^
main.cpp:49:24: error: no function template matches function template specialization 'second'
int& Pair<double,int>::second()

Any clue to what could be going wrong?



Solution 1:[1]

Since the other answer didn't explain why prefix template<> is not needed here, i will try to provide that explanaition in my answer.

Solution to the Problem

As discussed below, we just need to remove the template<> prefix as shown below:

//no prefix template<> needed here
inline double& Pair<double,int>::first()
{
    return a;
}

//no prefix template<> needed here
inline int& Pair<double,int>::second()
{
    return b;
}

Working demo

Note that the inline keyword is added so that we don't get multiple definition error since usually we implement the templates in header files which are then included in multiple source files.

Explanation of the Problem

The reason we don't need the prefix template<> is that we're providing an ordinary out-of-class definition for the member functions of a full class template specialization. That is, we're not actually specializing the member functions but instead providing an ordinary(non-template) out of class definition for those member functions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1