C++ template

Templates in C++ are a powerful feature that allows you to write generic and reusable code. In this tutorial, we'll cover function templates, class templates, and variable templates.

Function Templates

Function templates allow you to define a function that can operate on any data type. The syntax is straightforward:

template <typename T>
T maxFunc(T a, T b) {
  cout << "function template, <T>: ";
  return (a > b) ? a : b;
}

You can use this template function with different data types

cout << maxFunc(5.5, 2.3) << endl; // double
cout << maxFunc<double>(10, 20) << endl; // explicitly specify the type

Function Templates with Multiple Types

You can also create function templates with multiple type parameters:

template <typename T1, typename T2>
void combine(T1 a, T2 b) {
  cout << "function template, two types, <T1, T2>: " << a << ", " << b << endl;
}

This function template takes two parameters of different types and prints them:

combine<double, string>(5.5, "hello you");

Class Templates

Class templates allow you to create a class that can operate with any data type:

template <typename T>
class MaxClass {
  T a;
  T b;
public:
  MaxClass(T a, T b) : a(a), b(b) {}
  T maxFunc() {
    cout << "class template, <T>: ";
    return (a > b) ? a : b;
  }
};

You can use this class template with different data types:

cout << MaxClass(5.5, 2.3).maxFunc() << endl;
      cout << MaxClass(10, 20).maxFunc() << endl;

Class Templates with Multiple Types

You can also create class templates with multiple type parameters:

template <typename T1, typename T2>
class MyClass2 {
  T1 a;
  T2 b;
public:
  MyClass2(T1 a, T2 b) : a(a), b(b) {}
  void combine() {
    cout << "class template, two types, <T1, T2>: " << a << ", " << b << endl;
  }
};

You can instantiate this class template with different data types:

MyClass2<double, string>(5.5, "hello you").combine();

Variable Templates

Variable templates were introduced in C++14. They allow you to create variables that depend on template parameters:

template <typename T>
          constexpr T pi = T(3.1415926535897932385);

You can use this variable template with different types:

cout << "Variable template: pi<int> = " << pi<int> << endl;
          cout << "Variable template: pi<double> = " << pi<double> << endl;

Complete Example