6.1. Parameterized Types

Here is a nontemplate declaration of the BTnode class in which the stored value is a string class object. I call it string_BTnode because we must define other instances that store values of type int, double, and so on.

class string_BTnode { 
public: 
    //  ... 
private: 
   string _val; 
   int _cnt; 
   int_BTnode *_lchild; 
   int_BTnode *_rchild; 
}; 

Without the template mechanism, each type would need its own separately implemented BTnode class, and each would need to be named uniquely.

The template mechanism allows us to separate the type-dependent and invariant portions of our class definition. The code that traverses the tree, inserts and removes nodes, and maintains the occurrence count is the same regardless of the value’s type. ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.