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:
1 2 3 4 5 6 7 8 9 10 11 |
// declaring the stack class template <class T> class Stack { // ... }; // This is an instance of stack storing integers Stack<int> integerStack // This is an instance of stack storing strings Stack<std::string> stringStack |
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
1 2 3 4 5 6 |
void swap(int& a, int& b) { int temp = a; a = b; b = temp; } |
and then create an almost identical overload taking two doubles, one overload taking two strings, etc. Or you could just create one template function:
1 2 3 4 5 6 7 |
template<typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; } |
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):
1 2 3 4 5 6 7 8 9 10 11 |
int a = 5; int b = 7; // swap to integers, the type is determined by the compiler swap(a, b); std::string x = "hello "; std::string y = "world"; // swap two strings swap(x, y) |
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;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
template <typename T> void func(T x) { // ... } // func is called with the type char* func("hello world"); // func is called with the type std::string func<std::string>("hello world"); // func is called with the type std::string func(std::string("hello world")); |


