Parameterized Types u Without Template, we have to implement multiple BTNode classes with different names and data types For those insertion, deletion and traversing ops, their mechanism won't change when node data type changes thus are type- independent? a We extract the "type-dependent"parts and parameterize them
Parameterized Types ◼ Without Template, we have to implement multiple BTNode classes with different names and data types ◼ For those insertion, deletion and traversing ops, their mechanism won’t change when node data type changes, thus are “typeindependent” ◼ We extract the “type-dependent” parts and parameterize them
Parameterized Types(cont) template< typename valtype class btnode //forward declaration template typename valtype class btnode //class definition public The valtype in Class template is used as a space reserver pI rivate valtype m Val a It's a type parameter that int m icnt could replace any built-in BTNode* Child BTNode* rchild type or user-defined type }; while running
Parameterized Types (cont.) template < typename valtype > class BTNode; //forward declaration //… template < typename valtype > class BTNode //class definition { public: //… private: valtype m_Val; int m_iCnt; BTNode* lchild; BTNode* rchild; }; ◼ The valtype in class template is used as a space reserver ◼ It’s a type parameter that could replace any built-in type or user-defined type while running
Parameterized Types(cont) template typename elemtype> class Binary Tree //forward declaration template typename valtype class btnode public pI rivate friend class binary Tree<valtype>
Parameterized Types (cont.) template < typename elemtype > class BinaryTree; //forward declaration template < typename valtype > class BTNode { public: //… private: //… friend class BinaryTree<valtype>; };
Parameterized Types(cont) u To generate entity class from the class template, real types should be provided in the template parameter list(<>) which the type parameter would bind to ■ Usage BTNode< int bti BTNode< string btS a bti and bts are different objects from different classes
Parameterized Types (cont.) ◼ To generate entity class from the class template, real types should be provided in the template parameter list(<>) which the type parameter would bind to ◼ Usage BTNode< int > bti; BTNode< string > bts; ◼ bti and bts are different objects from different classes
Parameterized Types(cont) u Definition of class BinaryTree template< typename elemtype class Binary Tree public private BTNode<elemtype>*m root a When we need to add template parameter list after the class template? a Except in the definition of class template and its member functions
Parameterized Types (cont.) ◼ Definition of class BinaryTree template < typename elemtype > class BinaryTree { public: //… private: //… BTNode<elemtype>* m_root; }; ◼ When we need to add template parameter list after the class template? ◼ Except in the definition of class template and its member functions