0
votes

I can't tell which part of this code is wrong. Error message is given below.

I want to overload the << operator so that I can write code like cout << tree. I looked up for information about templates, friend functions, operator overloading. But I still don't get why the error.

template <typename Value>
class Tree {
   protected:
    Node<Value>* root = NULL;
    int size = 0;
    std::ostream& _ostreamOperatorHelp(Node<Value>* node, int level,
                                       std::ostream& os) {
        ...
    }

   public:
    friend std::ostream& operator<< <Value>(std::ostream& os,
                                           Tree<Value> const& tree);
};

template <typename Value>
std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree) {
    tree._ostreamOperatorHelp(tree.GetRoot(), 0, os);
    return os;
}

Error message:

Tree.hpp:129:34: error: declaration of 'operator<<' as non-function
     friend std::ostream& operator<< <Value>(std::ostream& ,
                                  ^~
1

1 Answers

2
votes

Before you can befriend specific template specialization, you have to declare the general template function first like this:

template <typename Value>
class Tree;

template <typename Value>
std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree);

template <typename Value>
class Tree {
   protected:
    Node<Value>* root = NULL;
    int size = 0;
    std::ostream& _ostreamOperatorHelp(Node<Value>* node, int level,
                                       std::ostream& os) {
        ...
    }

   public:
    friend std::ostream& operator<< <Value>(std::ostream& os,
                                           Tree<Value> const& tree);
};

template <typename Value>
std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree) {
    tree._ostreamOperatorHelp(tree.GetRoot(), 0, os);
    return os;
}