Tuesday, November 29, 2011

C++ Tutorial: Templates

C++ Template is one of the most sophisticated, flexible and powerful feature. It was not the original feature of C++ as it was added later  on. The older versions of compilers do not support this feature.  Templates support generic programming, allowing development of reusable software components with functions and classes, supporting deferent data types in a single framework.
In C++, templates allow a type as a parameter in the definition of a function or a class. For example, if the same operation is to be performed with different data types then we need to write the same code for the different data types.This causes redundant code in the program with only difference in data type. For example, if we need to write functions for swap or sort that support different data types then we need to make functions for all different data types. Similarly, if we need to make a vector class that supports different data types, then we need to make classes each data type. But with the template mechanism, we can make a single sort or swap function that takes type as a parameter. The template declared for function are called function templates and those declared for classes are called class templates.

No comments:

Post a Comment