Operator >> Error

Hi I am having a problem with separating my overloaded operator into the .cpp of my class.

main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
   test<double> testObject;
   cin >> testObject
    return 0;
}


test.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;

template <class T>
class test
{
    friend istream &operator >>(istream &Input, test<T> &x);
    //If i put the code here it works fine
     public:

     private:
        T ** testArr;


test.cpp
1
2
3
4
5
6
7
8
#include <iostream>
#include "test.h"
using namespace std;

template<class T>
 istream &operator >>(istream &userIn, matrix<T> &obj){

}


The Error that I get is
undefined reference to `operator>>(std::istream&, matrix<double>&)'|
You declared the friend function as a non-template function inside class test however in the cpp file you are declaring it as a template function.

I think that the declaration should look the following way


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;

template <class T>
class test
{
    template <typename U>
    friend istream & operator >>(istream &, test<U> & );
    //If i put the code here it works fine
     public:

     private:
        T ** testArr;

....

template<class T>
istream & operator >>( istream &userIn, matrix<T> &obj )
{
    return ( userIn );
} 


Also do not forget to place all definitions of the template class in this header.
Last edited on
Okay I understand but is it possible to place all the definition inside the test.cpp instead of the header?
The main shall see the definitions that to generate an instantiation of a template.
In english: You need to have template definitions in headers.
@Stewbond Thank you lol
Topic archived. No new replies allowed.