Beginning templates

Templates are a terrific functionality in C++ which is used way too little! A template is a pattern for how a class or function taking a particular type should be created.  Lets say that you need a class which holds a stack of integers, you can simply create this as a regular class. If you later discover that you also need a class which holds a stack of  strings then you are forced to create a new class which does exactly the same thing but just using a different type of data. Creating two classes which does exactly the same thing is really wasting your time as a developer! The solution here is to create a template class; by doing so you create a pattern for how your stack class should work, but you don’t say the exact type that you will be working on.

To make a template class representing a stack, simply add the template keyword when declaring the class:


Template function

Just like you can create a template class, it is also possible to make a template function where the type of the inputs is determined at compile time, when the function is being called. Say that you want to create a function to swap two variables, you could either create one function to swap two integers

and then create an almost identical overload taking two doubles, one overload taking two strings, etc. Or you could just create one template function:

To call the template swap you don’t need to explicitly give the type of the variables (as you have to do when instantiating a template class):

Sometimes however, you may want to help the compiler determining the type of the variable. Say that you are calling a function with a literal string where the compiler would generate the template function with the type char* but you would much rather have the template function work on std::string. Then you can either tell the compiler that the type of the template function is std::string, or promote the literal string into a std::string;



Leave a Reply

Your email address will not be published. Required fields are marked *