C++ Templates Introduction
In this page:
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?
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
template <typename T>
void show(T value) {
std::cout << value << std::endl;
}
int main() {
show(5);
show("hello");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: