Thursday, August 4, 2016

Why is Templates :-)

Templates

Why :-)

We use templates when we need functions/classes that apply the same algorithm to a several types. So we can use the same function/class regardless of the types of the argument or result.

In other words, a template is a mechanism that allows a programmer to use types as parameters for a class or a function. The compiler then generates a specific class or function when we later provide specific types as arguments. In a sense, templates provide static (compile-time) polymorphism, as opposed to dynamic (run-time) polymorphism. A function/class defined using template is called a generic function/class, and the ability to use and create generic functions/classes is one of the key features of C++.

We can think of a class template as a type generator. The process of generating types from a class template is called specialization or template instantiation.

In most of the cases, template instantiation is very complicated, but that complexity is in the domain of compiler writer, not the template user. Template instantiation takes place at compile time or link time, not at run time.
,,,

Specialization or Template Instantiaion

The process of generating types from a given template arguments is called specialization or template instantiation. For example, vector<int> and vector<Node*> are said to be a specialization of vector.

,,,


Generic Programming --Template

Polymorphism

OOP--class hierarchies & virtual functions

Templates are the foundation of generic programming. Generic programming relies on polymorphism. Though there are several differences between OOP (class hierarchies and virtual functions) and generic programming (templates), the major difference is:

  1. Generic (templates) : compile time resolution. 
     The choice of function invoked when we use is determined by the compiler at compile time.
  2. OOP (virtual functions) : run time resolution.
Generic programming lets us write classes and functions that are polymorphic across unrelated types at compile time. A single class or function can be used to manipulate objects of a variety of types. The standard library containers, iterators, and algorithms are examples of generic programming. We can use library classes and functions on any kind of type.

When we parameterize a class, we get a class template, and when we parameterize a function, we get a function template.


So, what do people actually use template for?
  • When performance is essential.
  • When flexibility in combining information from several types is essential.
But note that, the flexibility and performance come at the cost of poor error diagnostics and poor error messages.
,,,










No comments:

Post a Comment