01 / 21
<T> f(T x)

C++ Function
Templates

Write one function that works with any data type: learn how the compiler generates type-safe code from a single blueprint.

C++

The Repetition Problem

Imagine you need a function that returns the larger of two values. Without templates you would write separate overloads for every type:

C++
int    maxVal(int a, int b)    { return (a > b) ? a : b; }
double maxVal(double a, double b){ return (a > b) ? a : b; }
char   maxVal(char a, char b)  { return (a > b) ? a : b; }

What Is a Function Template?

A function template is a blueprint that tells the compiler: "here is the logic; plug in whatever type is needed." The compiler then generates actual functions for each type used.

Blueprint
You write the template once with a placeholder type.
Instantiation
The compiler generates a concrete function for each type you call it with.
Type Safety
Each generated function is fully type-checked at compile time.

Key Vocabulary

1
Template parameter: a placeholder name (commonly T) that stands in for any type.
2
Template argument: the real type (e.g., int, double) substituted for T.
3
Instantiation: the compiler's act of creating a concrete function from the template for a specific type.
4
Implicit deduction: the compiler figures out T from the arguments you pass, without you specifying it.

Template Syntax

C++
template <typename T>
T maxVal(T a, T b) {
    return (a > b) ? a : b;
}
template <typename T> T maxVal (T a, T b) Declares a type parameter T used as return type & parameter type

How Instantiation Works

template<typename T> T maxVal(T a, T b) T = int int maxVal(int, int) T = double double maxVal(double, double) T = string string maxVal(string, string) Called with: maxVal(3, 7) Called with: maxVal(2.5, 9.1) Called with: maxVal("hi","bye") All generated at compile time: zero runtime cost

typename vs class

typename T class T
Meaning T is any type T is any type
Works with int, double, etc. ✓ ✓
Works with class/struct ✓ ✓
Convention Modern preferred Legacy, still common

How to Write a Template

1
Identify repeated logic: find overloads or copy-pasted code that differ only in type.
2
Add the template header: write template<typename T> above the function.
3
Replace the concrete type with T in the return type and parameter list.
4
Call the function normally. The compiler deduces T, or you specify it explicitly.
5
Verify constraints: ensure that T supports the operations used (e.g., operator>).

Example 1: Generic Swap

C++
template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 5, y = 10;
    mySwap(x, y);      // T = int

    std::string s1 = "hello", s2 = "world";
    mySwap(s1, s2);    // T = std::string
}

Example 2: Multiple Type Parameters

Templates can have more than one type parameter. Use distinct names like T and U:

C++
template <typename T, typename U>
void printPair(T first, U second) {
    std::cout << first << ", " << second << "\n";
}

// Usage:
printPair(42, "hello");   // T=int, U=const char*
printPair(3.14, 100);    // T=double, U=int

Example 3: Deduced Return Type

In C++14 and later you can let the compiler deduce the return type with auto:

C++14
template <typename T, typename U>
auto add(T a, U b) {
    return a + b;
}

auto r1 = add(3, 4.5);    // double (int + double)
auto r2 = add(1, 2);      // int    (int + int)

Implicit vs Explicit Calls

C++
template <typename T>
T square(T x) { return x * x; }

// Implicit deduction:
square(5);           // T = int
square(2.5);         // T = double

// Explicit specification:
square<double>(5);  // T = double (5 promoted)
Implicit
Compiler deduces T from arguments. Cleaner syntax, preferred when unambiguous.
Explicit
You write func<Type>(...). Needed when deduction would be wrong or ambiguous.

When Deduction Fails

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

maxVal(3, 4.5);  // ERROR: T=int or T=double?

Both arguments must yield the same T. The compiler sees int and double and cannot pick one.

Fix 1: Explicit call
maxVal<double>(3, 4.5);
Fix 2: Cast argument
maxVal(static_cast<double>(3), 4.5);
Fix 3: Two parameters
Use template<typename T, typename U> instead.

Templates vs Overloading

Function Template Overloading
Code written Once Once per type
Type safety Compile-time Compile-time
Logic varies per type? No: same logic Yes: each can differ
Performance Same as hand-written Same as hand-written
Error messages Can be verbose Clear and direct

Common Mistakes

✕ Separate header/source
Putting the template definition in a .cpp file causes linker errors. Keep templates in header files.
✕ Mismatched argument types
Calling maxVal(3, 4.5) when both params are T fails deduction. Cast or add a second parameter.
✕ Assuming all ops exist
If T doesn't support operator>, the template won't compile for that type.

Quick Reference Summary

Concept Syntax / Detail
Declare template template<typename T>
Multiple params template<typename T, typename U>
Implicit call maxVal(3, 7)
Explicit call maxVal<double>(3, 7)
Where to define In header files (.h / .hpp)
Constraint check Ensure T supports all used operators

Question 1 of 5

What is the primary purpose of a function template in C++?

Question 2 of 5

Given the template below, what is the output?

template <typename T>
T triple(T x) { return x * 3; }

std::cout << triple(4);

Question 3 of 5

Why does maxVal(3, 4.5) fail to compile when maxVal uses a single template<typename T>?

Question 4 of 5

Where should a function template's definition be placed?

Question 5 of 5

What does the following code print?

template <typename T, typename U>
auto add(T a, U b) { return a + b; }

std::cout << add(2, 3.5);