Overloading operator<< in friend function

If I have a template class called object_class, and I want to overload the operator << by using a friend function, I would use the code below within the header file:

1
2
3
4
5
6
7
8
9
10
11
12
13

template < class ItemType>
class object_class
{

  public:

  ...
  //Why do we need a new template class type for the friend function below?
  template <class friendItemType>
  friend ostream& operator<<(ostream& outputStream, const object_class< friendItemType >& output);

};


If inside the header file, the template class object_class has template type <ItemType>, then my book says I cannot use <ItemType> again in the friend function parameter that overloads operator<< (code above), so I have to create a new template with new type <friendItemType>. This is because operator << is not a part of object_class.

My question is, why does it matter? Isn't <ItemType>, the template type of object_class already an arbitrary type? Why do we need two arbitrary types? And a new template class within another class at that?

Last edited on
Templates are weird. If you define template classes completely inline you don't have to worry about some of the weirdness.
1
2
3
4
5
6
7
8
9
10
template<typename T>
struct MyClass
{
    //...

    friend std::ostream &operator<<(std::ostream &os, MyClass const &mc)
    {
        return os << mc.blah1 << " " << mc.blah2;
    }
};
What is the full name of your book, by the way?
Last edited on
What is the full name of your book, by the way?


My book is called Data Abstraction & Problem Solving with C++ walls and mirrors.
Last edited on
Topic archived. No new replies allowed.