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

C++ Templates Introduction

Templates let you write code once that works for many types, like a cookie cutter that can cut any dough. The compiler makes the version you need.
Syntax
cpp
template <typename T>
return_type function_name(T param) {
  // works with any type T
}

template <typename T>
class ClassName {
  T member;
};

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 std::cout and std::cin
#include <iostream>

// Declare a template so this works with any suitable type
template <typename T>
T maxValue(T a, T b) {
	// Send (a > b) ? a : b back to the caller
	return (a > b) ? a : b;
}

// Program execution starts in main()
int main() {
	// Print to the console with cout
	std::cout << maxValue(3, 7) << std::endl;
	// Print to the console with cout
	std::cout << maxValue(3.5, 2.5) << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Declare a template so this works with any suitable type
template <typename T>
T add(T a, T b) {
	// Send a + b back to the caller
	return a + b;
}

// Program execution starts in main()
int main() {
	// Print to the console with cout
	std::cout << add(2, 3) << std::endl;
	// Print to the console with cout
	std::cout << add(2.5, 3.5) << std::endl;
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Declare a template so this works with any suitable type
template <typename T>
void show(T value) {
	// Print to the console with cout
	std::cout << value << std::endl;
}

// Program execution starts in main()
int main() {
	show(5);
	show("hello");
	// Return 0 to signal that the program finished successfully
	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 std::cout and std::cin
#include <iostream>

// Declare a template so this works with any suitable type
template <typename T>
T square(T x) {
	// Send x * x back to the caller
	return x * x;
}

// Program execution starts in main()
int main() {
	// Print to the console with cout
	std::cout << square(4) << std::endl;
	// Print to the console with cout
	std::cout << square(2.5) << std::endl;
	// Return 0 to signal that the program finished successfully
	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;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting template definitions in a .cpp file and getting linker errors, since templates usually belong in headers.
  2. Forgetting template <typename T> before the definition.
  3. Expecting a template to be compiled once and work for any type, when it is instantiated separately for each type used.
🔒

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.