模板类运算符重载多个类型名称C ++

时间:2018-07-30 07:13:16

标签: c++ c++11 templates g++ operator-overloading

在surf.h中有我的后续代码,其中声明了具有两种不同类型的模板类:

using namespace std;    
template <typename T1, typename T2>

class surf;

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov);

template <typename T1, typename T2>
class surf
{
public:
    surf(T1 v1, T2 v2):
    v1_(v1),
    v2_(v2)
    {}

    friend ostream & operator << <T1, T2> (ostream & str, surf<T1,T2> & ov);

    T1 v1_;
    T2 v2_;

};

template <typename T1, typename T2>
ostream & operator << (ostream & str, surf<T1,T2> & ov)
{
    str << "("<<ov.v1_<<","<<ov.v2_<<")";
    return str;
}

typedef surf<int,double> intSurf;

然后定义一个新类,在其中创建类型为T的向量(在field.h中)

   template<typename T>
class field;

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov);

template<typename T>
class field
{
public:

    field( int n, T val):
        f_(n,val)
        {}

    friend ostream & operator << <T> (ostream & str, const field<T> & ov);
protected:

    vector<T> f_;
};

template<typename T>
ostream & operator << (ostream & str, const field<T> & ov)
{
    for(auto &fE: ov.f_)
    {
        str << fE << endl;
    }
    return str;
}

typedef field<intSurf> surfField;

,在main.cpp中,我使用此字段。

#include "field.h"

int main()
{

    surfField a(4, intSurf(2,5));   

    cout<< a << endl;

    return true;
}

我使用g ++(5.4版)进行编译,并收到以下错误:

在main.cpp包含的文件中:2:0: field.h:在‘std :: ostream&运算符<<(std :: ostream&,const field&)的实例中[T = surf; std :: ostream = std :: basic_ostream]’: main.cpp:9:9:从这里开始 field.h:36:7:错误:“ operator <<”不匹配(操作数类型为“ std :: ostream {aka std :: basic_ostream}”和“ const surf”)    str << fE << endl;

我在做什么?

1 个答案:

答案 0 :(得分:2)

您因const超载而错过了operator <<

template <typename T1, typename T2>
ostream & operator << (ostream & str, const surf<T1,T2> & ov);
//                                    ^^^^^
//...
friend ostream & operator << <T1, T2> (ostream & str, const surf<T1,T2> & ov);
//                                                    ^^^^^
//...
template <typename T1, typename T2>
ostream & operator << (ostream & str, const surf<T1,T2> & ov)
//                                    ^^^^^
//...

此const是必需的,因为您尝试显示来自const field<T> & ov

的元素