1

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)

41Ku5
  • 11
  • 1
  • 1
    See [documentation on `friend`](http://en.cppreference.com/w/cpp/language/friend). – chris Aug 30 '15 at 02:32
  • Note on the duplicate: [**this answer**](http://stackoverflow.com/a/4661372/1322972) is better than the selected one. – WhozCraig Aug 30 '15 at 02:49

0 Answers0