c++ - 显式模板特化错误

标签 c++ templates

这个应该很简单。我正在使用模板,但遇到编译器错误。

#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/

相关文章:

c++ - 多态性 - 不确定使用模板的派生类 - 派生函数返回模板类型

c++ - 类中的静态模板函数

c++ - SDL 在 OSX lion 上与终端/g++ 链接错误

c++ - 标志 ios_base::app 的错误行为

c++ - 由于意外的模板参数类型推导而导致的无限递归

c++ - 如何更好地处理依赖于模板参数的类成员类型?

c++ - 打印对象的文本表示

c++ - 这个 _com_ptr_t move 分配有什么目的吗?

c++ - select(NULL, NULL, NULL, &timeout) 只是等待给定的时间吗?

C++模板类的函数