codegurukool.com · Free coding tutorials & online compiler

Home › C++ Tutorial › C++ templates

C++ templates

One function for many types.

template <typename T> lets the compiler generate code for each type you use.

Example code

#include <iostream>
using namespace std;
template <typename T>
T bigger(T a, T b) { return a > b ? a : b; }
int main() {
  cout << bigger(3, 9) << " " << bigger(2.5, 1.5) << " " << bigger<string>("a", "b") << endl;
  return 0;
}

Run this code in the online editor

← C++ polymorphismC++ files →