6.5 A Function Template Output Operator
We'd like to provide an output operator for our BinaryTree class template. For a nontemplate class, we write
ostream& operator<<( ostream&, const int_BinaryTree& );
For the class template, we could provide an explicit instance for each generated class definition:
ostream& operator<<( ostream&, const BinaryTree<int>& );
But that's Sisyphus work: It's tedious, and it never ends. A better solution is to define the output operator as a
function template:
template <typename elemType>
inline ostream&
operator<<( ostream &os, const BinaryTree<elemType> &bt )
{
os << "Tree: " << endl;
bt.print( os );
return os;
}
When we write
BinaryTree< string > bts;
cout << bts << endl;
an instance of the output operator is generated to support a second parameter of BinaryTree<string>. When we write
BinaryTree< int > bti;
cout << bti << endl;
an instance of the output operator is generated to support a second parameter of BinaryTree<int>, and so on.
print() is a private member function of the BinaryTree class template (refer to the online code listing for its definition). For the output operator to access print(), it must be made a friend of BinaryTree:
template <typename elemType>
class BinaryTree {
friend ostream& operator<<( ostream&,
const BinaryTree<elemType>& );
// ...
};
|