Templates

Templates and the need for header only code

In one of our previous lessons, we built our own "vector", but it was specifically designed to only hold integers. But what if we wanted to store float, or char, or bool? This can be accomplished by using templates in C++.

Without a template

With a template

Here is how you would use the code and have the C++ compiler multiply your code for different types:

Sample 1

When you design your header file, especially with a template, your code can be input right within the class itself.

Sample 2

Source Code Organization

Template code in header file only

The way templates work is that for each type, such as vector<int> or vector<bool>, the entire header file is copied and pasted by the compiler for the new type. Because of this reason, classes that use templates must be in header file only. This means that you cannot have vector.hh and also vector.cc because the entire code has to exist in the header file only.

Standard code

Standard code that doesn't use templates can be in file.hh and also file.cc and doesn't need to be in a header. Although not that many libraries sometimes tend to be header only and the code split to file.cc is for cosmetic reasons only.

And then there should be a separate *.cc file or *.cpp file:

 

Back to top