模板函数中的运算符<<重载

operator << overloading in a template function

本文关键字:lt 重载 运算符 函数      更新时间:2023-10-16

我无法判断这段代码的哪一部分是错误的。下面给出了错误消息。

我想重载<<运算符,以便我可以像cout << 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;
}

错误信息:

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

在与特定的模板专用化交朋友之前,您必须先像这样声明通用模板函数:

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;
}