using template class c++ code example

Example 1: c++ template function

template <class T>
void swap(T & lhs, T & rhs)
{
 T tmp = lhs;
 lhs = rhs;
 rhs = tmp;
}

Example 2: templates classes in c++

// function template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

int main () {
  int i=5, j=6, k;
  long l=10, m=5, n;
  k=GetMax<int>(i,j);
  n=GetMax<long>(l,m);
  cout << k << endl;
  cout << n << endl;
  return 0;
}

Example 3: c++ class template

#include <vector>

// This is your own template
// T it's just a type
template <class T1, class T2, typename T3, typename T4 = int>
class MyClass
{
  public:
  	MyClass() { }
  
  private:
  	T1 data; 		// For example this data variable is T type
  	T2 anotherData;	// Actually you can name it as you wish but
  	T3 variable;	// for convenience you should name it T
}

int main(int argc, char **argv)
{
  std::vector<int> array(10);
  //          ^^^
  // This is a template in std library
  
  MyClass<int> object();
  // This is how it works with your class, just a template for type
  // < > angle brackets means "choose" any type you want
  // But it isn't necessary should work, because of some reasons
  // For example you need a type that do not supporting with class
  return (0);
}

Example 4: use of template in c++

// If two characters are passed to function template, character with larger ASCII value is displayed.

#include <iostream>
using namespace std;

// template function
template <typename T>
T Large(T n1, T n2)
{
	return (n1 > n2) ? n1 : n2;
}

int main()
{
	int i1, i2;
	float f1, f2;
	char c1, c2;

	cout << "Enter two integers:\n";
	cin >> i1 >> i2;
	cout << Large(i1, i2) <<" is larger." << endl;

	cout << "\nEnter two floating-point numbers:\n";
	cin >> f1 >> f2;
	cout << Large(f1, f2) <<" is larger." << endl;

	cout << "\nEnter two characters:\n";
	cin >> c1 >> c2;
	cout << Large(c1, c2) << " has larger ASCII value.";

	return 0;
}