Beginner’s Guide to C++ Templates – 1
I was job searching a few months back and one of the positions I tried for was of a C++ developer. I come from a BE degree in IT and MS degree in CS and I have studied C and C++ in engineering. My first job was as a C developer so while stepping into C++ I was confident that this would be easy. But as I was going through books, the documents on-line and the rest I quickly realised that I know very little of C++. That’s when I came across this book which said C++ has 4 parts which are
- The C part of C++
- The Object oriented part of C++
- The C++ templates
- The STL.
Whenever I looked around for information on templates and STL I wasn’t given much helpful guidance. That’s when I realised that there might be people like me out there who want to learn C++ templates and eventually C++ STL but they might not have the required leads and documents on-line. This is my attempt to help people like me.
Ok enough about the thought process let’s get started.
Firstly let us discuss about the syntax this whole less than and greater than symbols which was frankly quite putting off while in engineering. But let us brave through it. Templates largely use the angle brackets: The less than ( < ) and the greater than ( > ) operators. It is used in this format < Content >.
Content can be
- Class T / Typename T
- A data type which is of type T or mapping to T
- An integral specification
- An integral constant / pointer / reference which maps to specification
Symbol T means any data type a basic data type or UDT.
Let us see an example. Suppose you want to add two integers, this is the piece of code that does it
int add_double(int num1, int num2)
{
int result = num1 + num2;
return result;
}
Now to add two doubles, this is written
double add_double(double num1, double num2)
{
double result = num1 + num2;
return result;
}
Note here that the basic behavior is the same which is add two numbers, but we have to create and maintain two functions because of different types of numbers. Now if there was some way which would reduce this repetition of code and maintenance of code then we can reduce the appearance of repeated bugs in the same piece of code. The issue here is that for all the data types that exist one is needed to write that many functions all have the same functionality which is adding. It is in this situation that templates come to rescue. Template code removes repetitive writing of same logic for different data types by making the type generic. Let us see the template code
template<typename T >
T add(T n1, T n2)
{
T res = n1 + n2;
return res;
}
We are telling the compiler that the function add takes two inputs of type T and returns a type T. The compiler on seeing the template usage splits the compilation process into two parts. First part is basic check of syntax, semicolons, proper use of keywords. For the second part of compilation the compiler will instantiate code for that data type and then perform the compilation on that part.
Example: Imagine that the template that we just created is called like this
int main()
{
cout<<add(3,4); //adding two integers
cout<<add(4.5,3.2); //adding two doubles
cout<<add(add(3,4),add(2,3)); //adding two integers which is result of two other function calls
}
The first case is addition of two integers. So the compiler instantiates the template code for integers like
int add(int n1, int n2);
The second case is addition of two doubles. Compiler makes this copy
double add(double n1, double n2);
The third case is same as first case. Here the compiler has one copy of the integer code and calls that three times.
So from this discussion we can take away that we can avoid unnecessary code duplication and code maintenance issues with templates which is better that use of macros and void pointer functions. Templates are type safe and they reduces code-bloat. Only code which will be used is generated by the compiler.
You guys can try to create other function templates. Try a function template for printdouble where you take a number and print the double of it..This is a simple exercise to know your understanding. Please note that its only when you practice that you get it. Go ahead and write some code.
In the next part we will cover more about types of templates. I will increase the complexity of the guide as we progress. Not sure how many parts I plan to have..
Very Good 🙂
Thank you Manju 🙂