-1

I cannot understand what is template class used for? I am new to c++. Can I get a detail explanation.

// constructing unordered_sets
#include <iostream>
#include <string>
#include <unordered_set>

template<class T>
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }

std::unordered_set<std::string> second ( {"red","green","blue"} );    // init list
std::unordered_set<std::string> third ( {"orange","pink","yellow"} ); // init list
std::unordered_set<std::string> fourth ( second );
std::unordered_set<std::string> fifth ( cmerge(third,fourth) );       // move
Akash Chandra
  • 375
  • 1
  • 4
  • 13

1 Answers1

0

C++ template class/function is basically a generic class/function i.e., you just have to define the class or function once and you can use this definition for different data types(int,char,float etc). for Example:-

#include <iostream>
using namespace std;

// One function works for all data types.  This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
   return (x > y)? x: y;
}

int main()
{
  cout << myMax<int>(3, 7) << endl;  // Call myMax for int
  cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
  cout << myMax<char>('g', 'e') << endl;   // call myMax for char

  return 0;
}
Rahul Das
  • 26
  • 3