Friday, July 16, 2010

Function Templates

Function templates are functions that are parameterized so that they represent a family of functions; it means that we can have the same functional behavior for different data types.

They start with the keyword "template"
 template   template  inline T const& max(T const& a, T const& b) {  return a <>
The process of replacing template parameters by concrete types is called "instantiation", and mere use of a function template will trigger instantiation; it means that we don't have to instantiate it manually. Templates are compiled twice:
  1. Without instantiation
  2. At the time of instantiation (Can break the regular rules of compile/link)
When we call a function tempalate the template parameters are determined by the arguments we pass, in this case the compiler follows a procedure called "Argument deduction" All the parameters that we pass to a template must conform to the same datatype, there is no capability for type promotion for example max(4, 4.0) will fail instead we have to write max(4, 4.0) Function templates have two kinds of parameters
  1. Template parameters T, one type of template parameters are "type parameters" that are declared using "typename" keyword
  2. Call parameters
Because the types of the call parameters are constructed from the template parameters, template and call parameters are usually related. WE call this concept "function template argument deduction" Like ordinary functions, function templates can be overloaded
  inline int const& max (int const& a, int const& b) {   return a <> inline T const& max(T const& a, T const& b) {   return a <> inline T const& max(T const& a, T const& b, T const& c) {   return ::max (::max(a, b), c); }

No comments:

Post a Comment