Hi, I'm trying to overload the << operator in a template class, but I seem to be running into a few problems. The function has to be a friend function because I need to access private member variables in the function. Yes, this is for an assignment, but I have replicated the problem below so that it's not my assignment that you would be working on, jus the basic principal:
In main.cpp:
Code:
#include "example.h"
#include <ostream>
int main() {
Example<int> example_instance_1(55);
cout << example_instance_1 << endl;
return 0;
}
In file example.h:
Code:
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <ostream>
using namespace std;
template <class T> class Example {
template <class T> friend ostream& operator << (ostream& out, const Example<T>& ex);
public:
Example(T a); //constructor
private:
T a;
};
#include "example.template"
#endif
In file example.template:
Code:
#include <iostream>
using namespace std;
template <class T> ostream& operator << (ostream& out, const Example<T>& ex) {
cout << ex.a;
return out;
}
template <class T> Example<T>::Example(T a) {
this->a = a;
}
During compilation:
Code:
ps@ps-desktop:~/Desktop/untitled folder$ g++ main.cpp -o main -Wall
In file included from main.cpp:1:
example.h:7: error: declaration of ‘class T’
example.h:6: error: shadows template parm ‘class T’
ps@ps-desktop:~/Desktop/untitled folder$
If anyone could shed some light on what these errors mean and/or how to fix them it would be much appreciated.
-Nova
Bookmarks