Skip to content
Justice Tech School

Function Templates

Templates write one function for many types.

Example
#include <iostream>
#include <string>

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

int main() {
  std::cout << maxOf(3, 9) << " " << maxOf(2.5, 1.5) << " " << maxOf<std::string>("a", "b") << "\n";
  return 0;
}

Result

9 2.5 b

Exercise

Template keyword.

 <typename T>

Quiz Test

What does T stand for?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.