What are templates used for?

Hi there:
 I hope u'll be fine. Template functions are used to reuse a single function for multiple data types. I would give the example of the commonly used swap function that takes two parameters and swaps the values of both. Normally for the swap of two integers, this function would look like

void Swap(int &x, int &y)
  int temp = x;
  x = y;
  y = temp;

But what if u need to swap the values of two float variables or char variables or double variables and so on? Will u write the same code again and again for different data types?

That is where template functions come into play. There is no need to write the same code again and again only due to different data types. Just convert ur Swap function into a template function and it'll automatically work according to the data type of parameters passed. The prototype of this template function would look like

template <class T)
void Swap(T &x, T &y)
  T temp = x;
  x = y;
  y = temp;

Now the above funtion will work perfectly for all the basic data types.

Exactly similar is the concept of template classes. Template classes can store and manipulate the data of any data type. For example, if u implement the linklist class as a template class, it will work perfectly to store int/char/float.... data.

Plz. feel free to ask a followup, if u need to.
Thanks for contacting me


All Answers

Answers by Expert:

Ask Experts




I can answer any questions that range from the very basics of c++ to the advanced topics like polymorphism, inheritance, composition, multiple inheritance and templates. I can also answer almost every type of questions about c++ data structures like stack, queue, circular queue, linklist(single, double, circular), binary trees, binary search trees, avl trees, 2-3 and 2-3-4 trees. I dont have much experience of mfc and creating guis in visual c++, so plz. dont ask me questions about that.


I'm working in c++ since the last 6 years. I've good working skills specially in the advanced topics like inheritance, polymorphism and all type of c++ data structures.

©2017 About.com. All rights reserved.