Template in C++ is very interesting topic. Templates allow you to define functions and Classes that have parameters for type names. This article is about C++ templates, its types and its usage.
What is template?
Templates allow us to define generic classes. Template is mechanism which allows us to use one function or class to handle many different data types. Types of templates: Function templates, Class templates. Templates are compiled on-demand, so if your project uses piece of code that uses templates then you will able to instantiate template only when that piece of code is called.
Why it is needed?
By using templates we can design a single class or function that operates on data of many types, instead of having to create a separate class or function for each type. When used with functions they are known as function templates, whereas when used with classes they are called class templates.
Advantages of Templates
1) We are not required to type each type function. The compiler creates them from generic version that we pass on to it. This makes the listing shorter & easier to understand.
2) If we are to modify the function we need to make changes at only one place in the listing instead of four places.
1) Many Compilers have trouble with separate compilations of template, so you need to include template definition along with the code that uses it. Or you can place the template definition in separate file and #include the file in your main application program.
2) If your compilers have different requirements then use the compiler manual for usage of templates.
3) Template is new feature introduced by ANSI-C++ standard. If your compiler is pre-ANSI standard then you can’t use this feature. Upgrade to latest compiler that supports updated ANSI-C++ standard.
When you are using templates with functions then they’re called function templates. Function templates can be of type: over-riding, multiple argument type.
See the below example:
template <class T >
T min( T a, T b)
int i=10, j=20;
char ch=’a’, dh=’z’;
Class templates are usually used for data storage (container) classes. Stacks & linked lists are examples of container classes. Class templates allow us to store different data types in a single class.
The syntax for defining an object of template class is –
Class-name <type> objectname (argumentlist)
The general format of a class template is-
template <class T>
//class member specification
//with anonymous type T
If you want more information you can look up at cplusplus website. Other than that you can get ask your question at daniweb & techiwarehouse forums.
I hope information above helped. If you’ve any suggestions or feedback regarding this article then please do not hesitate to submit.