01 / 21
<T>

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.

C++

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.

Template <T> Blueprint func<int> func<double> func<string> Concrete Concrete Concrete

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.

✓ Code Reuse
Write once, use with any compatible type: no copy-paste needed.
✓ Type Safety
The compiler checks types at compile time: no runtime casts or surprises.
✓ Performance
Templates generate specialized code: zero overhead compared to hand-written versions.

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:

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; }

Template Syntax

The core declaration uses the keyword template followed by angle brackets containing a type parameter:

template < typename T > keyword declares a type placeholder name
template <typename T> T maxVal(T a, T b) { return (a > b) ? a : b; }

Template Instantiation

When you call a template function, the compiler generates a concrete version by substituting the type parameter. This process is called instantiation.

maxVal<T>(T, T) maxVal(3, 7) T = int maxVal(2.5, 9.1) T = double maxVal('a', 'z') T = char int maxVal(int,int) double maxVal(double,double) char maxVal(char,char)

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

Function Template
Parameterizes a single function. The compiler deduces T from arguments.
Class Template
Parameterizes an entire class. You must specify T explicitly: Box<int>.
// Function template template <typename T> T add(T a, T b) { return a + b; } // Class template template <typename T> class Box { T value; public: Box(T v) : value(v) {} T get() { return value; } };

Multiple Type Parameters

Templates can accept more than one type parameter. Separate them with commas inside the angle brackets.

template <typename T, typename U> class Pair { T first; U second; public: Pair(T f, U s) : first(f), second(s) {} }; // Usage: Pair<int, double> p(1, 3.14);

How to Write a Template

1
Identify the varying type. Find which type changes across copies of the function or class.
2
Add the template header. Write template<typename T> immediately above the function or class.
3
Replace the concrete type with T. Swap every occurrence of int (or whichever type varies) with T.
4
Call or instantiate. Use the template: the compiler deduces or you specify the type.

Example 1: Generic Swap

Let's template a function that swaps two variables. The logic is identical for any type.

template <typename T> void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; } // Works with any type: int x = 5, y = 10; mySwap(x, y); // T = int string s1 = "hi", s2 = "bye"; mySwap(s1, s2); // T = string

Example 2: Generic Stack

A class template that implements a simple stack for any type:

template <typename T> class Stack { vector<T> data; public: void push(T val) { data.push_back(val); } T top() { return data.back(); } void pop() { data.pop_back(); } }; // Usage: Stack<int> intStack; Stack<string> strStack;

Example 3: Two-Type Convert

A function template with two type parameters that converts one type to another:

template <typename Target, typename Source> Target convert(Source val) { return static_cast<Target>(val); } // Must specify Target; Source is deduced: int n = convert<int>(3.14); // n = 3 double d = convert<double>(42); // d = 42.0

Default Type Parameters

Just like function parameters can have defaults, template type parameters can too:

template <typename T = int> class Container { T value; public: Container(T v) : value(v) {} }; Container<> c1(42); // T = int (default) Container<double> c2(3.14); // T = double

Common Mistakes

✕ Mismatched Arguments
Calling maxVal(3, 2.5) fails: the compiler cannot deduce T as both int and double. Fix: use maxVal<double>(3, 2.5).
✕ Missing Operations
Using \(>\) inside a template but passing a type that has no \(>\) operator causes a compile error. Ensure T supports needed operations.
✕ Separating Declaration
Putting the template definition in a .cpp file causes linker errors. Templates must be defined in header files so the compiler can see the full definition.

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)?

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

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?

template <typename T> T add(T a, T b) { return a + b; } int main() { std::cout << add(2, 3) << " "; std::cout << add(1.5, 2.5); }