C Template
   HOME

TheInfoList



OR:

Templates are a feature of the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different
data types In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
without being rewritten for each one. The
C++ Standard Library The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard.ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it wa ...
provides many useful functions within a framework of connected templates. Major inspirations for C++ templates were the parameterized modules provided by CLU and the generics provided by
Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, Tur ...
.


Technical overview

There are three kinds of templates: ''function templates'', ''class templates'' and, since
C++14 C++14 is a version of the ISO/IEC 14882 standard for the C++ programming language. It is intended to be a small extension over C++11, featuring mainly bug fixes and small improvements, and was replaced by C++17. Its approval was announced on August ...
, ''variable templates''. Since
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
, templates may be either
variadic In computer science, an operator or function is variadic if it can take a varying number of arguments; that is, if its arity is not fixed. For specific articles, see: * Variadic function * Variadic macro in the C preprocessor * Variadic template ...
or non-variadic; in earlier versions of C++ they are always non-variadic.


Function templates

A ''function template'' behaves like a function except that the template can have arguments of many different types (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, 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: template T max(T &a, T &b) This single function definition works with many data types. Specifically, it works with all data types for which > (the greater-than operator) is defined. 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. A template does not produce smaller 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 shown 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: #include 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(). This function template can be instantiated with any copy-constructible type for which the expression y > x is valid. For user-defined types, this implies that the greater-than operator (>) must be overloaded in the type.


Class templates

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement
containers A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping. Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
. A class template is instantiated by passing a given set of types to it as template arguments. The C++ Standard Library contains many class templates, in particular the containers adapted from the
Standard Template Library The Standard Template Library (STL) is a Library (computer science), software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components ...
, such as
vector Vector most often refers to: *Euclidean vector, a quantity with a magnitude and a direction *Vector (epidemiology), an agent that carries and transmits an infectious pathogen into another living organism Vector may also refer to: Mathematic ...
.


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 In computer programming, a standard library is the library made available across implementations of a programming language. These libraries are conventionally described in programming language specifications; however, contents of a language's as ...
fixed-size
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
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 std::size_t (representing the number of elements the array holds). std::array 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 Specialization or Specialized may refer to: Academia * Academic specialization, may be a course of study or major at an academic institution or may refer to the field in which a specialist practices * Specialty (medicine), a branch of medical ...
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. * If a class template is specialized by a subset of its parameters it is called
partial template specialization Partial template specialization is a particular form of class template specialization. Usually used in reference to the C++ programming language, it allows the programmer to specialize only some arguments of a class template, as opposed to explici ...
(function templates cannot be partially specialized). * If all of the parameters are specialized it is a ''full specialization''. 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*: #include template<> const char* max(const char* a, const char* b)


Variadic templates

C++11 introduced
variadic template In computer programming, variadic templates are templates that take a variable number of arguments. Variadic templates are supported by C++ (since the C++11 standard), and the D programming language. C++ The variadic template feature of C++ was de ...
s, which can take a variable number of arguments in a manner somewhat similar to
variadic function In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages. The term ''varia ...
s such as std::printf.


Template aliases

C++11 introduced template aliases, which act like parameterized
typedef typedef is a reserved keyword in the programming languages C, C++, and Objective-C. It is used to create an additional name (''alias'') for another data type, but does not create a new type, except in the obscure case of a qualified typedef of ...
s. The following code shows the definition of a template alias StrMap. This allows, for example, StrMap to be used as shorthand for std::unordered_map. template using StrMap = std::unordered_map;


Generic programming features in other languages

Initially, the concept of templates was not included in some languages, such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
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 C++ templates. Some of the advanced template features utilized by libraries such as Boost and STLSoft, and implementations of the STL itself, for
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
(explicit or partial specialization, default template arguments, template non-type arguments, template template arguments, ...) are not available 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. // Induction template 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,
constexpr C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
in C++11 / consteval in C++20 can be used to calculate such values directly using a function at compile-time. Because of this, template meta-programming is now mostly used to do operations on types.


See also

*
Template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
*
Metaprogramming Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
*
Monomorphization In programming languages, monomorphization is a compile-time process where polymorphic functions are replaced by many monomorphic functions for each unique instantiation. This transformation is desirable, since then the output intermediate represe ...
*
Generic programming Generic programming is a style of computer programming in which algorithms are written in terms of types ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as parameters. This approach, pioneered b ...
*
Header-only In the context of the C or C++ programming languages, a library is called header-only if the full definitions of all macros, functions and classes comprising the library are visible to the compiler in a header file form. Header-only libraries do ...
* Substitution failure is not an error *
Curiously recurring template pattern The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a f ...
* List of C++ template libraries


References


External links


Demonstration of the Turing-completeness of C++ templates
(Lambda calculus implementation) {{DEFAULTSORT:Template (Programming) Generic programming Metaprogramming C++ Articles with example C++ code