Wednesday, 23 March 2011

templates

Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types . This allows a function or class to work on many different data types without being rewritten for each one.
Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading.
types of the templates:
1. function templates
2. generic classes or classes
3. explicit template specialization
2 Advantages and disadvantages
3 Generic programming features in other languages

Function templates

A function template behaves like a function except that the template can have arguments of many different types (see example). In other words, a function template represents a family of functions. For example, the C++ Standard Library contains the function template max(x, y) which returns either x or y, whichever is larger. max() could be defined like this, using the following template:
#include <iostream>
 
template <typename T>
const T& max(const T& x, const T& y)
{
  if(y < x)
    return x;
  return y;
}
 
void main()
{
  // This will call max <int> (by argument deduction)
  cout << max(3, 7) << std::endl;
  // This will call max<double> (by argument deduction)
  cout << max(3.0, 7.0) << std::endl;
  // This type is ambiguous; explicitly instantiate max<double>
  cout << max<double>(3, 7.0) << std::endl;
  getch();
}

No comments:

Post a Comment