← Back to C++ Course | Chapter 11: Templates | Lesson 1 of 5

C++ Templates Introduction

What are Templates?

Templates let you write genuinely generic code in C++ — a single class or function definition that can work with essentially any data type, with the compiler generating the type-specific version you actually need behind the scenes.

Example: What are Templates?

cpp
#include <iostream>

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

int main() {
	std::cout << maxValue(3, 7) << std::endl;
	std::cout << maxValue(3.5, 2.5) << std::endl;
	return 0;
}

Code Reusability

Without templates, you'd have to hand-write nearly identical overloaded functions for every type you want to support — one for int, one for float, one for double. A template collapses all of those into one definition that the compiler specializes automatically for whichever type you use it with.

Example: Code Reusability

cpp
#include <iostream>

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

int main() {
	std::cout << add(2, 3) << std::endl;
	std::cout << add(2.5, 3.5) << std::endl;
	return 0;
}

Template Parameters

Inside a template's angle brackets, the typename or class keyword introduces a placeholder for a type, which the compiler substitutes with the real type you provide (or one it infers) wherever that placeholder appears in the template's body.

Example: Template Parameters

cpp
#include <iostream>

template <typename T>
void show(T value) {
	std::cout << value << std::endl;
}

int main() {
	show(5);
	show("hello");
	return 0;
}

Compile-Time Generation

Templates are instantiated at compile time: the compiler examines the types you actually use a template with and generates a distinct, fully optimized version of that function or class for each one — there's no runtime overhead from the genericity itself.

Example: Compile-Time Generation

cpp
#include <iostream>

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

int main() {
	std::cout << square(4) << std::endl;
	std::cout << square(2.5) << std::endl;
	return 0;
}

Type Safety with Templates

Unlike older techniques such as void pointers or preprocessor macros, templates are strictly type-checked by the compiler at the point of instantiation, catching type errors during compilation rather than letting them slip through to crash the program at runtime.

Example: Type Safety with Templates

cpp
#include <iostream>

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

int main() {
	std::cout << add(3, 4) << std::endl;
	// add(3, "text"); would fail to compile: type mismatch caught at compile time
	return 0;
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.