Template Type
Parameters
Learn how C++ templates let you write one function or class that works with any data type: the foundation of generic programming.
What Is a Template?
A template is a blueprint that tells the compiler: "I will define the exact type later: for now, use a placeholder." This lets you write code once and reuse it for int, double, string, or any type you need.
Why Templates Matter
Without templates, you would need to write separate functions for every type. Templates eliminate this duplication and form the backbone of the C++ Standard Library.
The Problem Without Templates
Imagine you need a function that returns the larger of two values. Without templates, you must write a separate function for each type:
Template Syntax
The core declaration uses the keyword template followed by angle brackets containing a type parameter:
Template Instantiation
When you call a template function, the compiler generates a concrete version by substituting the type parameter. This process is called instantiation.
typename vs class
You will see two keywords used to declare type parameters. In practice, they are interchangeable for template type parameters.
| typename T | class T | |
|---|---|---|
| Meaning | T is any type | T is any type |
| Works with int, double | ✓ | ✓ |
| Works with classes | ✓ | ✓ |
| Modern convention | Preferred | Older style |
Function vs Class Templates
Box<int>.Multiple Type Parameters
Templates can accept more than one type parameter. Separate them with commas inside the angle brackets.
How to Write a Template
Example 1: Generic Swap
Let's template a function that swaps two variables. The logic is identical for any type.
Example 2: Generic Stack
A class template that implements a simple stack for any type:
Example 3: Two-Type Convert
A function template with two type parameters that converts one type to another:
Default Type Parameters
Just like function parameters can have defaults, template type parameters can too:
Common Mistakes
maxVal(3, 2.5) fails: the compiler cannot deduce T as both int and double. Fix: use maxVal<double>(3, 2.5).Summary Table
| Feature | Function Template | Class Template |
|---|---|---|
| Syntax | template<typename T> T func(...) |
template<typename T> class Name {...} |
| Type deduction | Automatic | Explicit (pre-C++17) |
| Multiple params | ✓ | ✓ |
| Default types | ✓ | ✓ |
| Defined in | Header file | Header file |
| STL example | std::sort, std::swap | std::vector, std::map |
Question 1 of 5
What does the T represent in template<typename T>?
Question 2 of 5
Given the template below, what happens when you call maxVal(3, 2.5)?
maxVal<double>(3, 2.5).Question 3 of 5
Which of these is true about typename vs class in a template parameter list?
Question 4 of 5
Why must template definitions typically be placed in header files rather than .cpp files?
Question 5 of 5
What is the output of the following code?