I was trying to overload the OSTREAM operator like this:
#include <iostream>
using namespace std;
template <typename T>
class MyClass
{
public:
MyClass(){};
friend ostream& operator << (ostream&,const MyClass<T>&);
};
template<typename T>
ostream& operator << (ostream& out , const MyClass<T>& source)
{
out << "it works";
return out;
}
int main ()
{
MyClass<int> test;
cout << test;
return 0;
};
and I'm getting a warning and an error
the warning:
warning: friend declaration βstd::ostream& operator<<(std::ostream&,const MyClass<T>&)β declares a non-template function [-Wnon-template-friend]
friend ostream& operator << (ostream&,const MyClass<T>&);
the error:
undefined reference to `operator<<(std::ostream&, MyClass<int> const&)'
what i don't get it, if I'm using a template function why the compiler doesn't find my template function?
and why when i implement something like this:
#include <iostream>
using namespace std;
template <typename T>
class MyClass
{
public:
MyClass(){};
friend ostream& operator << (ostream& out,const MyClass<T>& source)
{
out << "it works" << endl;
return out;
}
};
int main ()
{
MyClass<int> test;
cout << test;
return 0;
};
the compiler has no problem finding my template function,
so how should i do the overload if i don't want to implement it inside of the class? (like the second code, and implement like the first one)