Generics in C++: What Are Templates and How to Use Them for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Generics in C++: Why They Are Needed and How to Use Them



Hello, friend! If you are just starting to learn C++ and have already encountered the concept of Generics (or templates), then this article is for you. Many beginners are afraid of templates, considering them something complex and magical. In reality, everything is much simpler. Let's figure out what they are, why they are needed, and how to use them in practice.



What Are Generics (Templates) in C++?



Imagine you need to write a function that adds two numbers. You write one function for int, another for double, a third for float… Agreed, this is tedious and violates the DRY (Don't Repeat Yourself) principle.



This is where templates come to the rescue. This is a mechanism that allows you to write generic code that works with any data type. In C++, this is the equivalent of what other languages call Generics (for example, in Java or C#).



A template is not a specific function or class, but a "blueprint" or "recipe." The compiler, seeing that you are using a template with the int type, creates a version of the code for int. If you use it with double, the compiler creates a version for double. This is called template instantiation.



Why Are Templates Needed? Three Main Reasons



1. Code Reusability

Instead of writing 10 functions for different numeric types, you write one universal one. This saves time, reduces the number of errors, and makes the code more readable.



2. Type Safety

Unlike macros (#define) or using void*, templates are checked by the compiler. If you try to pass an unsuitable type to a template, the compiler will give an error at compile time, not during program execution.



3. Performance

Templates do not add runtime overhead. The compiler creates optimized code for each specific type, and this code runs as fast as if you had written it manually.



How to Use Templates: Syntax and Examples



Let's look at two main types of templates: function templates and class templates.



Function Templates

The simplest example is a function that finds the maximum of two values.



#include <iostream>#include <string>

// Declaring a function templatetemplate <typename T>T max_value(T a, T b) { return (a > b) ? a : b;}

int main() { // Works with int std::cout << max_value(10, 20) << std::endl; // Output: 20 // Works with double std::cout << max_value(3.14, 2.71) << std::endl; // Output: 3.14 // Works with strings std::cout << max_value(std::string("apple"), std::string("banana")) << std::endl; // Output: banana return 0;}


The keyword template tells the compiler: "Attention, a template follows." <typename T> is the list of template parameters. T is a placeholder name for the type, which will be replaced with the actual type when the function is called. Instead of typename, you can use class — there is no difference.



Important: The compiler deduces which type you mean from the passed arguments. This is called template argument deduction. But you can specify the type explicitly:



std::cout << max_value<double>(10, 20.5) << std::endl; // Explicitly specifying the double type


Class Templates

Class templates allow you to create universal data containers. A classic example is a simple analog of std::pair.



#include <iostream>#include <string>

// Template

Blogs

Book Recommendations