• Embed Doc
  • Readcast
  • Collections
  • 3
    CommentGo Back
Download
 
 An Introduction to C++ Templates
Why Templates?
Generic programming has become a dominant programming paradigm in C++, particularly after the incorporation of the Standard Template Library (STL) as part of the standard library in 1996.Templates - the language feature that supports generic programming in C++ - was originallyconceived for supporting ‘parameterized types’ (classes parametrized by type information) inwriting container classes.Templates are a compile time mechanism. Because of this, there is no runtime overheadassociated with using them. Also, using templates is completely type safe. Templates help toseamlessly integrate all types and thereby let programmers write code for one (generic) type. So,it serves as a mechanism for writing high-level reusable code, which is known as ‘genericprogramming’. Like the structured, modular and object oriented programming approaches,generic programming is another programming approach (and C++ supports all these fouprogramming paradigms! For this reason, C++ is referred to as a ‘multi-paradigm’ language).
Writing Reusable Code
Two primary means of providing reusable functionality in conventional object-oriented systems isthrough inheritance and composition. Inheritance refers to creating subclasses or subtypes fromexisting classes and composition refers to providing objects of other class types as datamembers. "
Parameterized types give us a third way (in addition to class inheritance and object composition) to compose behavior in object-oriented systems. Many designs can beimplemented using any of these three techniques
", observes [Gamma et al, 1994]. Templateslook at the problem of reusability in a different way - it uses type independence as the basisrather than inheritance, polymorphism and composition.One of the main objectives of C++ is to support writing low-level code for systems programmingin which performance is an important consideration. C++ templates do not add any additionalperformance overheads and still promises high level of reusability; hence, templates havebecome very important in C++ for writing reusable code.
Use of Templates
The (re)use of tested and quality template code can save us from lots of programming effort andcan be helpful in variety of programming tasks. The three important advantages of usingtemplates are:
type safety (as strict type checking is done at compile time itself),
reusability (as writing code for one generic type is enough) and
performance (as templates involve no runtime overheads).There are many other advantages of using templates and they are discussed in detail later in thisarticle.To illustrate the usefulness of templates, let us take an example from the C standard library. Toget the absolute value of a number we need different functions, one for each type. For integerswe use
abs
, for floating point numbers
fabs
, and for complex numbers
cabs
. If polymorphicfacilities were available in C, such inventing of new names would not have been necessary (andlife could have been easier for the programmer). How about using overloading in C++ for thisproblem? Consider:
 
int abs(int);long abs(long);double abs(double);complex abs(complex);
Yes, in this case, we need not reinvent new names, but still almost same code is duplicated inthese functions; so, overloading is not a very good solution.How about using overriding? No, it cannot help us in for this requirement since these functionsdiffer in their argument and return type, and overriding requires that the signature remains thesame.Using templates could elegantly solve this problem. Using
function template
s, it is enough to writegeneric code for one function:
template <class T>T abs(T arg) {return ((arg < 0) ? –arg : arg);}
With this definition, the compiler will take care of creating copies (known as
template
 
instantiation
)for specific types as and when required in the program. For example, when given
abs(12)
or 
abs(doubleVar)
, the compiler is smart enough to instantiate (or make use of the one if alreadyinstantiated) the right function for that type and resolve it in the compile time itself.In the beginning of the article, we mentioned that templates started with the desire to"parameterize" the containers. Such classes are known as ‘
class templates
’. A simple examplewould be a stack container parameterized by type T instead of providing separate classes like
int_stack
,
string_stack
,
double_stack
etc: 
template <class T>class stack {// the following members remain the samestack(int start_size = 10);stack(const stack&);stack& operator=(const stack&);~stack();int is_empty() const;int is_full() const;// templatizing these members using Tvoid push(const T& t);T& pop();private:T* stack;// Note T* hereint topOfStack;// following data members remain the sameint size;};
Templates can provide readymade implementations even for day-to-day programming activities(for example, consider 
std::for_each
function template in STL); hence it frees theprogrammer from reinventing the wheel and allows him to straightaway reuse what is available intemplates.Templates make it possible to write truly reusable components that can be modified with little
 
difficulty, still retaining type safety (ensuring type safety is an important objective of strongly typedlanguages).
Template Meta-programming
Let us take another example to see from different perspective. An important advantage of C++templates is its unimaginably expressive and powerful nature. Here is a simple (and well-known)example of template version of finding factorial of a number:
template <int num>struct Factorial {static const int fact =num * Factorial < num - 1 > :: fact;};// specialization for 0, which provides terminating conditiontemplate <>struct Factorial<0> {static const int fact = 1;};int main() {std::cout<< "The factorial of 3 is: " << Factorial<3>::fact;}// output://The factorial of 3 is: 6
Remember that template mechanism is a compile-time mechanism in C++. In this program, thereis a template for 
Factorial
with
non-type parameter 
int. There is a
template specialization
of 
Factorial
for value 0 -
template instantiation
is done for 3, 2, 1 and terminates at 0 as there isa specialization available. For finding the factorial of 3, with template instantiation, the value isfound at compile-time itself! This approach of programming is known as
meta-programming 
,which is an emerging programming approach in C++.Meta-programming is a difficult topic and it is possible to write sophisticated programs which docompile-time manipulations. Boost is a set of open-source libraries, mostly written based onmeta-programming approach. The factorial example given in this section is just for introducing thetopic and we’ll not cover it anymore in this article; if you are interested, please see the Boostwebsite (www.boost.org) for more details.
Advantages of Using Templates
Templates abstract type information (and non-type information too)
You can use primitive types, class types or templates themselves as arguments: in this way,templates offer maximum flexibility in their use. Consider:
template <int lines, int columns>class screen {char ** buffer;explicit screen(lines, columns) {buffer = new char[lines * columns];}// other members
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...

beneficial my friend thank you :)

You must be to leave a comment.
Submit
Characters: ...