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.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:- Generic (templates) : compile time resolution.
The choice of function invoked when we use is determined by the compiler at compile time. - OOP (virtual functions) : run time resolution.
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.
,,,
No comments:
Post a Comment