I l@ve RuBoard Previous Section Next Section

6.2 The Template Class Definition

Here is a partial definition of our BinaryTree class template:



template <typename elemType> 


class BinaryTree { 


public: 


    BinaryTree(); 


    BinaryTree( const BinaryTree& ); 


    ~BinaryTree(); 


    BinaryTree& operator=( const BinaryTree& ); 





    bool empty() { return _root == 0; } 


    void clear(); 


private: 


    BTnode<elemType> *_root; 





    // copy a subtree addressed by src to tar 


    void copy( BTnode<elemType>*tar, BTnode<elemType>*src ); 


}; 

Defining an inline member function for a class template is the same as for a nonclass template, as the definition of empty() illustrates. The syntax for defining a class template member function outside the class body, however, looks very different, at least at first blush:



template <typename elemType> 


inline BinaryTree<elemType>:: 


BinaryTree() : _root( 0 ) 


{} 

The member function definition begins with the template keyword and parameter list of the class. The function definition follows that, together with the inline qualifier and class scope operator. The inline qualifier must come after the template keyword and parameter list.

Why is the second occurrence of the BinaryTree name not qualified? After the class scope operator is seen,



BinaryTree< elemType >:: 

everything following that is treated as occurring inside the class definition. When we write



BinaryTree< elemType >::  // outside class definition 


BinaryTree()              // inside class definition 

the second occurrence of BinaryTree is considered within the class definition and so does not need to be qualified. For example, here are the definitions of the copy constructor, copy assignment operator, and destructor:



template <typename elemType> 


inline BinaryTree<elemType>:: 


BinaryTree( const BinaryTree &rhs ) 


      { copy( _root, rhs._root ); } 





template <typename elemType> 


inline BinaryTree<elemType>:: 


~BinaryTree() 


       { clear(); } 





template <typename elemType> 


inline BinaryTree<elemType>& 


BinaryTree<elemType>:: 


operator=( const BinaryTree &rhs ) 


{ 


    if ( this != &rhs ) 


       { clear(); copy( _root, rhs._root ); } 


    return *this; 


} 

You probably won't believe me, but after you write a sufficient number of these sorts of definitions, they begin to look almost natural.

    I l@ve RuBoard Previous Section Next Section