Templates in C++
Get a brief overview of templates in C++.
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.
Press + to interact
#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 ...