Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing overloads for >> and << operators in a template class

I'm trying to write the function definition for overloading the operators ">>" and "<<" outside of the class definition, though in the same file, as you can see. I get the following errors:

1>Source.obj : error LNK2019: unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class MyClass<int> &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$MyClass@H@@@Z) referenced in function _main
1>Source.obj : error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class MyClass<int>)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$MyClass@H@@@Z) referenced in function _main
1>Source.obj : error LNK2019: unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class MyClass<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$MyClass@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@Z) referenced in function _main
1>Source.obj : error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class MyClass<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$MyClass@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@Z) referenced in function _main

I've been up and down the river with this one. The strange thing is that if I write their definitions inside the class definition, it works flawlessly.

#include <iostream>
#include <string>
using namespace std;

template <class MYTYPE>
class MyClass {
    MYTYPE *myVector;
    int dim;
    string name;
public:
    MyClass(int, string);
    MyClass() {};
    friend istream& operator>>(istream&, MyClass<MYTYPE>&);
    friend ostream& operator<<(ostream&, MyClass<MYTYPE>);
};

template <class MYTYPE>
MyClass<MYTYPE>::MyClass(int x, string y) {
    dim = x;
    name = y;
    myVector = new MYTYPE[dim];
}


template <class MYTYPE>
istream& operator>>(istream& X, MyClass<MYTYPE>& a){
    cout<<"Reading vector: "<<a.name<<endl;
    for(int indice = 0; indice < a.dim; indice++){
        cout<<a.name<<'['<<indice<<"]= ";
        X >> a.myVector[indice];
    }
    return X;
}

template <class MYTYPE>
ostream& operator<<(ostream& X, MyClass<MYTYPE> a){
    X<<"Vector: "<<a.name<<endl;
    for(int indice = 0; indice < a.dim; indice++)
        X<<a.myVector[indice]<<' ';
        X<<endl;
    return X;
}


int main() {
    MyClass<int> object(4, "Ints vector");
    MyClass<string> object2(5, "String vector");
    cin >> object;
    cin >> object2;
    cout << object;
    cout << object2;
    system("pause");
    return 0;
}
like image 639
NeVada Avatar asked Jun 22 '17 21:06

NeVada


People also ask

Can stream operators << and >> can be overloaded?

The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object. Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object.

What is operator overloading explain the >> << operator with the help of example?

Operator Overloading in C++ This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Can overload is possible in template?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

Can we overload << operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.


3 Answers

It is a bit complicated. Actually there are two ways a class template can have a function friend.

For example, take this:

template <typename T>
void fun();

template <typename T>
class A
{
};

Then what do you want?

  1. Or do you want that func<X>() be friend of A<Y> for any other Y?
  2. Do you want that fun<X>() be friend of A<X> but not of A<Y>?

That is, should the function be able to access privater members of any specialization or only to the specialization of the same type.

My guess is that you need option 2. The trick is that you must make friend of the function specialization so the template function must already exist: you have declare the template function first and then make it friend. Something like:

//first declare both function and class
template <typename T>
class A;
template <typename T>
void fun();

//Then define the class
template <typename T>
class A
{
    //A<T> is friend to fun<T>, the specializations must match.
    friend void fun<T>();
};

//And define the function
template <typename T>
void fun()
{
}

If what you want is option 1, then there is no need of the advanced declarations. Just:

template <typename T>
class A
{
    //A<T> is friend to fun<X>, T and X may be different
    template <class X>
    friend void fun();
};

That said, your code is a bit tricky to write because of the << and the >>:

template <class MYTYPE>
class MyClass;

template <class MYTYPE>
istream& operator>>(istream& X, MyClass<MYTYPE>& a);

template <class MYTYPE>
ostream& operator<<(ostream&, MyClass<MYTYPE>);

template <class MYTYPE>
class MyClass {
    // ....
    friend istream& operator>> <MYTYPE>(istream&, MyClass<MYTYPE>&);
    friend ostream& operator<< <MYTYPE>(ostream&, MyClass<MYTYPE>);
};
like image 127
rodrigo Avatar answered Nov 12 '22 05:11

rodrigo


In your code, declarations of friend operators within MyClass should look like these:

template<typename T> friend istream& operator>>(istream&, MyClass<T>&);
template<typename T> friend ostream& operator<<(ostream&, MyClass<T>);

That is, they shall have their own template parameters.

A valid definition for MyClass based on the one provided in the question follows:

template <class MYTYPE>
class MyClass { 
    MYTYPE *myVector;
    int dim;
    string name;
public:
    MyClass(int, string);
    MyClass() {}

    template<typename T>
    friend istream& operator>>(istream&, MyClass<T>&);

    template<typename T>
    friend ostream& operator<<(ostream&, MyClass<T>);
};
like image 22
skypjack Avatar answered Nov 12 '22 05:11

skypjack


Turning up the warning level of the compiler helps. By using -Wall with g++, I get the following warnings before the linker error.

socc.cc:13:58: warning: friend declaration ‘std::istream& operator>>(std::istream&, MyClass<MYTYPE>&                    )’ declares a non-template function [-Wnon-template-friend]
     friend istream& operator>>(istream&, MyClass<MYTYPE>&);
                                                          ^
socc.cc:13:58: note: (if this is not what you intended, make sure the function template has already                     been declared and add <> after the function name here)
socc.cc:14:57: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, MyClass<MYTYPE>                     ’ declares a non-template function [-Wnon-template-friend]
     friend ostream& operator<<(ostream&, MyClass<MYTYPE>);

You need to use function templates for the operator>> and operator<< functions. You can declare them before the definition of the class with:

// Forward the class template.
template <class MYTYPE> class MyClass;

// Declare the function templates.
template <class MYTYPE> 
std::istream& operator>>(std::istream&, MyClass<MYTYPE>&);

template <class MYTYPE> 
std::ostream& operator<<(st::ostream&, MyClass<MYTYPE>);

Then, you'll have to use the friend declaration with the appropriate template parameter.

// This makes sure that operator>><int> is not a friend of MyClass<double>
// Only operator>><double> is a friend of MyClass<double>
friend std::istream& operator>><MYTYPE>(std::istream&, MyClass<MYTYPE>&);
friend std::ostream& operator<<<MYTYPE>(std::ostream&, MyClass<MYTYPE>);

Here's an updated version of your code that builds for me. I haven't tried to run it.

#include <iostream>
#include <string>
using namespace std;

template <class MYTYPE> class MyClass;

template <class MYTYPE> 
std::istream& operator>>(std::istream&, MyClass<MYTYPE>&);

template <class MYTYPE> 
std::ostream& operator<<(std::ostream&, MyClass<MYTYPE>);

template <class MYTYPE>
class MyClass {
    MYTYPE *myVector;
    int dim;
    string name;
public:
    MyClass(int, string);
    MyClass() {};

    friend std::istream& operator>><MYTYPE>(std::istream&, MyClass<MYTYPE>&);
    friend std::ostream& operator<<<MYTYPE>(std::ostream&, MyClass<MYTYPE>);
};

template <class MYTYPE>
MyClass<MYTYPE>::MyClass(int x, string y) {
    dim = x;
    name = y;
    myVector = new MYTYPE[dim];
}


template <class MYTYPE>
std::istream& operator>>(std::istream& X, MyClass<MYTYPE>& a){
    cout<<"Reading vector: "<<a.name<<endl;
    for(int indice = 0; indice < a.dim; indice++){
        cout<<a.name<<'['<<indice<<"]= ";
        X >> a.myVector[indice];
    }
    return X;
}

template <class MYTYPE>
std::ostream& operator<<(std::ostream& X, MyClass<MYTYPE> a){
    X<<"Vector: "<<a.name<<endl;
    for(int indice = 0; indice < a.dim; indice++)
        X<<a.myVector[indice]<<' ';
        X<<endl;
    return X;
}


int main() {
    MyClass<int> object(4, "Ints vector");
    MyClass<string> object2(5, "String vector");
    cin >> object;
    cin >> object2;
    cout << object;
    cout << object2;
    system("pause");
    return 0;
}
like image 43
R Sahu Avatar answered Nov 12 '22 05:11

R Sahu