Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator<<(ostream& os, ...) for template class

Why I cannot use the same template parameter for a friend function that takes a template argument? I mean the code below is OK!

template <class Vertex>
class Edge
{
   template <class T>
   friend ostream& operator<<(ostream& os, const Edge<T>& e);
   /// ...
};


template <class T>
ostream& operator<<(ostream& os, const Edge<T>& e)
{
   return os << e.getVertex1() << " -> " << e.getVertex2();
}

But this one is NOT ok. Why? What is the problem? (I get linker error.)

template <class Vertex>
class Edge
{
   friend ostream& operator<<(ostream& os, const Edge<Vertex>& e);
   /// ...
};

template <class T>
ostream& operator<<(ostream& os, const Edge<T>& e)
{
   return os << e.getVertex1() << " -> " << e.getVertex2();
}
like image 850
Narek Avatar asked Apr 22 '13 09:04

Narek


People also ask

What is ostream operator in C++?

std::ostream::operator<< Generates a sequence of characters with the representation of val , properly formatted according to the locale and other formatting settings selected in the stream, and inserts them into the output stream.

How do you overload cout?

To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.

What is the insertion operator in C++?

The insertion ( << ) operator, which is preprogrammed for all standard C++ data types, sends bytes to an output stream object. Insertion operators work with predefined "manipulators," which are elements that change the default format of integer arguments.

Which operator is overloaded for CIN?

Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.


1 Answers

You can use following

template <class Vertex>
class Edge
{
   friend ostream& operator<< <>(ostream& os, const Edge<Vertex>& e);
   /// ...
};

that makes operator << <Vertex> friend to Edge.

In your second case - you make friend non-template operator, but definition of this operator is template, so you have undefined reference, but this case can be used if you want your operator << for concrete Edge (Edge<int> for example).

like image 182
ForEveR Avatar answered Sep 22 '22 04:09

ForEveR