Template (C++) Explained

Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class declaration to reference via a generic variable another different class (built-in or newly declared data type) without creating a full declaration for each of these different classes.

In plain terms, a templated class or function would be the equivalent of (before "compiling") copying and pasting the templated block of code where it is used, and then replacing the template parameter with the actual one. For this reason, classes employing templated methods place the implementation in the headers (files) as no symbol could be compiled without knowing the type beforehand.

The C++ Standard Library provides many useful functions within a framework of connected templates.

Major inspirations for C++ templates were the parameterized modules provided by the language CLU and the generics provided by Ada.[1]

Technical overview

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

C++ Templates are Turing complete.[2]

Function templates

See main article: Typename. A function template behaves like a function except that the template can accept arguments of various types, enabling type-generic behavior (see example). In other words, a function template represents a family of functions. The format for declaring function templates with type parameters is:template Declaration;template Declaration;Both expressions have the same meaning and behave in exactly the same way. The latter form was introduced to avoid confusion,[3] since a type parameter need not be a class until C++20. (It can be a basic type such as int or double.)

For example, the C++ Standard Library contains the function template max(x, y) which returns the larger of x and y. That function template could be defined like this[4] :template nodiscardconstexpr T& max(const T& a, const T& b) noexcept This single function definition works with many data types. Specifically, it works with all data types for which < (the less-than operator) is defined and returns a value with a type convertible to bool. The usage of a function template saves space in the source code file in addition to limiting changes to one function description and making the code easier to read.

An instantiated function template usually produces the same object code, though, compared to writing separate functions for all the different data types used in a specific program. For example, if a program uses both an int and a double version of the max function template above, the compiler will create an object code version of max that operates on int arguments and another object code version that operates on double arguments. The compiler output will be identical to what would have been produced if the source code had contained two separate non-templated versions of max, one written to handle int and one written to handle double.

Here is how the function template could be used:import std;

int main

In the first two cases, the template argument T is automatically deduced by the compiler to be int and double, respectively. In the third case automatic deduction of max(3, 7.0) would fail because the type of the parameters must in general match the template arguments exactly. Therefore, we explicitly instantiate the double version with max<double>.

This function template can be instantiated with any copy-constructible type for which the expression y&nbsp;&lt;&nbsp;x is valid. For user-defined types, this implies that the less-than operator (&lt;) must be overloaded in the type.

Abbreviated function templates

Since C++20, using auto or [[concepts (C++)|concept]] auto in any of the parameters of a function declaration, that declaration becomes an abbreviated function template declaration.[5] Such a declaration declares a function template and one invented template parameter for each placeholder is appended to the template parameter list:// equivalent to:// template // void f1(T x);void f1(auto x);

// equivalent to (if Concept1 is a concept):// // void f2(T x);void f2(Concept1 auto x);

// equivalent to (if Concept2 is a concept):// template // void f3(Ts... xs)void f3(Concept2 auto... xs);

// equivalent to (if Concept2 is a concept):// template // void f4(T... xs);void f4(Concept2 auto xs, ...);

// equivalent to (if Concept3 and Concept4 are concepts):// template // f5(const T* t, U& u);void f5(const Concept3 auto* t, Concept4 auto& u);

Constraining the max using concepts could look something like this:

using std::totally_ordered;

// in typename declaration:template nodiscardconstexpr T max(T x, T y) noexcept

// in requires clause:template requires totally_orderednodiscardconstexpr T max(T x, T y) noexcept

Class templates

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.[6] The C++ Standard Library contains many class templates, in particular the containers adapted from the Standard Template Library, such as [[Vector (C++)|vector]].

Variable templates

In C++14, templates can be also used for variables, as in the following example:template constexpr T PI = T; // (Almost) from std::numbers::pi

Non-type template parameters

Although templating on types, as in the examples above, is the most common form of templating in C++, it is also possible to template on values. Thus, for example, a class declared with

template class MyClass;

can be instantiated with a specific int.

As a real-world example, the standard library fixed-size array type [[std::array]] is templated on both a type (representing the type of object that the array holds) and a number which is of type [[size_t|std::size_t]] (representing the number of elements the array holds). To create a class Array equivalent to std::array, it can be declared as follows:

template struct Array;

and an array of six chars might be declared:

Array myArray;

Template specialization

When a function or class is instantiated from a template, a specialization of that template is created by the compiler for the set of arguments used, and the specialization is referred to as being a generated specialization.

Explicit template specialization

Sometimes, the programmer may decide to implement a special version of a function (or class) for a given set of template type arguments which is called an explicit specialization. In this way certain template types can have a specialized implementation that is optimized for the type or a more meaningful implementation than the generic implementation.

Explicit specialization is used when the behavior of a function or class for particular choices of the template parameters must deviate from the generic behavior: that is, from the code generated by the main template, or templates. For example, the template definition below defines a specific implementation of max for arguments of type const char*:import std;

template <> nodiscardconstexpr const char* max(const char* a, const char* b) noexcept

Variadic templates

C++11 introduced variadic templates, which can take a variable number of arguments in a manner somewhat similar to variadic functions such as std::printf.

using std::format_string;using std::ofstream;

enum class Level ;

ofstream logFile;

template void log(const format_string& fmt, Args&&... args)

Because only C-style variadic parameters are supported in C++, the only way to get type-safe variadic functions (like in Java is through variadic templates.

Template aliases

C++11 introduced template aliases, which act like parameterized typedefs.

The following code shows renaming std::map to TreeMap and std::unordered_map to HashMap, as well as creating an alias StringHashMap for std::unordered_map<K, std::string>. This allows, for example, StringHashMap<int> to be used as shorthand for std::unordered_map<int, std::string>.

using String = std::string;

// allowing optional specialization of hash functions, allocators, etc.template < typename K, typename V, typename Compare = std::less, typename Alloc = std::allocator>>using TreeMap = std::map;

template < typename K, typename V, typename HashFn = std::hash, typename KeyEq = std::equal_to, typename Alloc = std::allocator>> using HashMap = std::unordered_map;

// or, only allowing K and V to be specialized:template using TreeMap = std::map;

template using HashMap = std::unordered_map;

// Defining StringHashMap = HashMaptemplate using StringHashMap = HashMap;

StringHashMap myMap = /* something here... */;

Constrained templates

Since C++20, templates can be constrained similarly to generics wildcards in Java or C# and Rust where clauses. This is done using concepts, which represent a set of boolean predicates evaluated at compile time.

For example, this code defines a concept representing an upper bound on inheritance. A class satisfies this concept if it inherits from Player, and classes that do not cannot be used as the template parameter in processListOfPlayers.import std;

using std::is_base_of_v;using std::vector;

class Player ;

template concept ExtendsPlayer = is_base_of_v;

// T is required to be a type whose inheritance upper bound is Player,// blocking any type that does not inherit from Playertemplate void processListOfPlayers(vector players)

Exported templates

In C++03, "exported templates" were added to C++.[7] These were later removed in C++11, due to very few compilers actually supporting the feature.[8] The only compiler known to support exported templates was Comeau C/C++. Among the cited reasons for removal were:

An "exported template" is essentially a class template whose static data members and non-inline methods are exported. It must be marked by the keyword export. What distinguishes an "exported template" is the fact that it does not need to be defined in a translation unit that uses the template.[9] [10] For example (in C++03):

  1. include

static void trace

export template T min(const T& x, const T& y);

int main

  1. include

static void trace

export template T min(const T& x, const T& y)

With the introduction of modules in C++20, the keyword export was re-added to C++. This re-allowed declarations like this:

import std;

using std::is_base_of_v;

export class Atom ;

export template concept ExtendsAtom = is_base_of_v;

export template class Cluster: public Bases... ;

The compilation speed benefits intended to be offered by exported templates are offered by modules anyway, making the feature essentially obsolete and superseded by modules.

Generic programming features in other languages

Initially, the concept of templates was not included in some languages, such as Java and C# 1.0. Java's adoption of generics mimics the behavior of templates, but is technically different. C# added generics (parameterized types) in .NET 2.0. The generics in Ada predate C++ templates.

Although C++ templates, Java generics, and .NET generics are often considered similar, generics only mimic the basic behavior of templates.[11] Some of the advanced template features utilized by libraries such as Boost and STLSoft, and implementations of the STL, for template metaprogramming (explicit or partial specialization, default template arguments, template non-type arguments, template template arguments, ...) are unavailable with generics.

In C++ templates, compile-time cases were historically performed by pattern matching over the template arguments. For example, the template base class in the Factorial example below is implemented by matching 0 rather than with an inequality test, which was previously unavailable. However, the arrival in C++11 of standard library features such as std::conditional has provided another, more flexible way to handle conditional template instantiation.

// Inductiontemplate struct Factorial ;

// Base case via template specialization:template <> struct Factorial<0> ;

With these definitions, one can compute, say 6! at compile time using the expression Factorial<6>::value.

Alternatively, [[C++11#constexpr – Generalized constant expressions|constexpr]] in C++11 / if constexpr in C++17 can be used to calculate such values directly using a function at compile-time:

template nodiscardconstexpr unsigned int factorial noexcept

Because of this, template meta-programming is now mostly used to do operations on types.

See also

External links

Notes and References

  1. Web site: Stroustrup . Bjarne . Bjarne Stroustrup . 8 September 2004 . The C++ Programming Language . 3rd, Special . Stroustrup.com (personal homepage).
  2. Web site: C++ Templates are Turing Complete. https://web.archive.org/web/20131101122512/http://ubietylab.net/ubigraph/content/Papers/pdf/CppTuring.pdf . 2013-11-01 . ubietylab.net.
  3. Web site: Lippman . Stan . 11 August 2004 . Microsoft Developers Network (MSDN) . Why C++ Supports both Class and Typename for Type Parameters.
  4. Web site: std::max . cppreference.com . July 21, 2025.
  5. Web site: P1141R1 - Yet another approach for constrained declarations. 2018-11-11. 2018-11-11. https://web.archive.org/web/20181111133625/http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p1141r1.html. live.
  6. Book: Vandevoorde . Daveed . Josuttis . Nicolai . C++ Templates: The Complete Guide . . 2002 . 978-0-201-73484-3.
  7. Web site: Class template. 7 October 2025. cppreference.com.
  8. Web site: Why We Can't Afford Export. Herb Sutter. open-std.org. WG 21. 3 March 2003.
  9. Web site: Export Overview. https://web.archive.org/web/20030602175841/http://www.comeaucomputing.com/4.0/docs/userman/export.html. 2 June 2003. usurped. comeaucomputing.com. Comeau Computing.
  10. Web site: Exported Template Overview. https://web.archive.org/web/20030422063923/http://www.c0meaucomputing.com/4.3.0/minor/win95+/43stuff.txt. 22 April 2003. usurped. comeaucomputing.com. Comeau Computing.
  11. Web site: Differences Between C++ Templates and C# Generics (C# Programming Guide). 12 March 2024.