⬅ Previous Next ➡

Templates in C++

Templates in C++
  • Templates allow writing generic code that works with different data types.
  • This concept is called generic programming (write once, use for int/float/double/string etc.).
  • Main types: function templates and class templates.

1) Function Templates

  • A function template creates a generic function for multiple data types.
  • Syntax:
    • template <typename T> T func(T a, T b)
    • typename and class are both valid for template type parameters.
#include <iostream>
using namespace std;

template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    cout << "Max(int): " << getMax(10, 20) << endl;
    cout << "Max(double): " << getMax(2.5, 1.7) << endl;

    return 0;
}

2) Template Parameters

  • Templates can have different parameter types:
  • Type parameter: template <typename T>
  • Non-type parameter: template <int N> (compile-time constant)
#include <iostream>
using namespace std;

template <int N>
void showSize() {
    cout << "N = " << N << endl;
}

int main() {
    showSize<5>();
    showSize<10>();
    return 0;
}

3) Class Templates

  • A class template creates a generic class for different data types.
#include <iostream>
using namespace std;

template <class T>
class Box {
    T value;

public:
    Box(T v) {
        value = v;
    }

    void show() {
        cout << "Value: " << value << endl;
    }
};

int main() {
    Box<int> b1(100);
    Box<double> b2(12.5);

    b1.show();
    b2.show();

    return 0;
}

4) Multiple Template Parameters

  • A template can accept more than one type parameter.
#include <iostream>
using namespace std;

template <typename T1, typename T2>
class PairData {
    T1 a;
    T2 b;

public:
    PairData(T1 x, T2 y) {
        a = x;
        b = y;
    }

    void show() {
        cout << a << " " << b << endl;
    }
};

int main() {
    PairData<int, string> p1(1, "Sourav");
    PairData<string, double> p2("Rate", 9.5);

    p1.show();
    p2.show();

    return 0;
}

5) Generic Programming Concept

  • Generic programming focuses on writing type-independent algorithms and data structures.
  • Examples:
    • STL containers: vector<T>, list<T>, map<K,V>
    • STL algorithms: sort(), find(), count()
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {5, 2, 9, 1};

    sort(v.begin(), v.end());

    for (int x : v) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}

6) Quick Notes

  • Function template = generic function.
  • Class template = generic class.
  • Template parameters can be type or non-type.
  • Templates are the base of STL and generic programming.
⬅ Previous Next ➡