这个应该很简单。我正在使用模板,但遇到编译器错误。
#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;
}
错误看起来像这样
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()
有什么可能出错的线索吗?
最佳答案
您不需要在方法声明之前声明模板<>。
double& Pair<double,int>::first() {
return a;
}
int& Pair<double,int>::second() {
return b;
}
应该够了。
关于c++ - 显式模板特化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928239/