Search⌘ K

Templates in C++

Explore how C++ templates enable generic programming by allowing functions and classes to handle multiple data types. Understand common problems with templates such as implicit requirements and confusing error messages. Discover the challenges of template specialization and how Concepts offer a scalable way to express precise constraints on template parameters for safer and more readable code.

What are templates?

Templates is a feature of the C++ programming language that allows functions and classes to deal with generic types. This allows a function or class to handle a wide range of data types without having to rebuild it.

Here is a simple function template to add two numbers of any type.

C++
#include <iostream>
template <typename T>
T add(T a, T b) {
return a+b;
}
int main() {
int a{42};
int b{66};
std::cout << add(a, b) << '\n';
long double x{42.42L};
long double y{66.6L};
std::cout << add(x, y) << '\n';
}

If we look at C++ Insights we’ll see that code was generated for both int and long double overload.

Template specialization

When a separate and unique implementation is required for a given data type, template specialization is used.

When we build a function or class template, the compiler generates a duplicate of it every time a class is used for a new data type.

If a ...