A “template” is instructions to the compiler on how to write code for you.
So, you could write a whole bunch of node classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
struct IntNode {
int data;
int count;
IntNode* left;
IntNode* right;
};
struct StringNode {
std::string data;
int count;
StringNode* left;
StringNode* right;
};
...
|
On top of that are all the functions and methods that work over every kind of node, and before long you have a gazillion lines of code all repeating themselves, where the
only difference between them is
the type of thing being stored in the node.
And then you discover you want to use a binary tree to store a
struct point, or some other thing that you never considered when you wrote the node classes.
C++ gets rid of that mess with templates. Write a single
templated class to tell the compiler how to write a specific, concrete class for whatever data type you want:
1 2 3 4 5 6 7
|
template <typename DataType>
struct Node {
DataType data;
int count;
Node<DataType>* left;
Node<DataType>* right;
};
|
The “
DataType” (or “
T” or whatever you name it) is a placeholder for the
type you wish to abstract. That is what the compiler will replace when it writes code for you.
Thereafter you can create a binary tree using any type of data you wish, even stuff that you never thought of when you were writing the template:
1 2 3 4
|
Node<int>* int_tree = nullptr;
Node<std::string>* string_tree = nullptr;
Node<point>* point_tree = nullptr; // whatever struct point looks like, you still get a valid binary tree class
// and so on
|
Hope this helps.