简体   繁体   中英

template class operator overloading multiple typenames C++

I have the followign code in surf.h in which a template class with two different types are declared:

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;

and then defined a new class in which a vector of type T is created (in 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;

and in main.cpp i use this field.

#include "field.h"

int main()
{

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

    cout<< a << endl;

    return true;
}

I compile it with g++ (version 5.4) and get the following error:

In file included from main.cpp:2:0: field.h: In instantiation of 'std::ostream& operator<<(std::ostream&, const field&) [with T = surf; std::ostream = std::basic_ostream]': main.cpp:9:9: required from here field.h:36:7: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'const surf') str << fE << endl;

What am I doing worng?

you were missing a const for your overload of 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)
//                                    ^^^^^
//...

this const is needed because you attempt to display elements coming from a const field<T> & ov

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM