Tsallaka zuwa abun ciki
Justice Tech School

Function Templates

A template writes one function for many types. The compiler generates a version for each type used.

Example
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
template <typename T, typename U>
auto add(T a, U b) { return a + b; }
int main() {
    cout << biggest(3, 9) << " " << biggest(2.5, 1.5) << " " << biggest<string>("a", "b") << "\n";
    cout << add(1, 2.5) << "\n";
}

Result

9 2.5 b
3.5

Exercise

Template keyword.

 <typename T>

Quiz Test

What is a template?

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