Interview Questions   Tutorials   Discussions   Programs   Videos   

C++ - What is a template?

asked marvit August 18, 2014 12:44 PM  

What is a template?


1 Answers

answered By bhjahnavi   0  
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.
an example for template is as follows:
/*an example template to demonstrate templates concept*/
#include <iostream>
#include <string>

using namespace std;

template <typename T>
inline T const& Max (T const& a, T const& b) 
  return a < b ? b:a; 
int main ()
  int i = 39;
  int j = 20;
  cout << "Max(i, j): " << Max(i, j) << endl; 

  double f1 = 13.5; 
  double f2 = 20.7; 
  cout << "Max(f1, f2): " << Max(f1, f2) << endl; 

  string s1 = "Hello"; 
  string s2 = "World"; 
  cout << "Max(s1, s2): " << Max(s1, s2) << endl; 

  return 0;
   add comment

Your answer

Join with account you already have



Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!