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();
}
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With