Template (C++)
≈ 9 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
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. 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.
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. 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. 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 nodiscard constexpr T& max(const T& a, const T& b) noexcept { return a This single function definition works with many data types. Specifically, it works with all data types for which 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() { // This will call max by implicit argument deduction. std::println("{}", std::max(3, 7)); // This will call max by implicit argument deduction. std::println("{}", std::max(3.0, 7.0)); // We need to explicitly specify the type of the arguments; // although std::type_identity could solve this problem... std::println("{}", max (3, 7.0)); } 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 less-than operator ( < ) must be overloaded in the type. Since C++20, using auto or concept auto (for a concept) in any of the parameters of a function declaration, that declaration becomes an abbreviated function template declaration. Such a declaration declares a function template and one invented template parameter for each placeholder is appended to the template parameter list: template void f1(T x); // equivalent to: void g1(auto x); void f2(T x); // equivalent to (if Concept1 is a concept): void g2(Concept1 auto x); template void f3(Ts... xs) // equivalent to (if Concept2 is a concept): void g3(Concept2 auto... xs); template void f4(T... xs); // equivalent to (if Concept2 is a concept): void g4(Concept2 auto xs, ...); template void f5(const T* t, U& u); // equivalent to (if Concept3 and Concept4 are concepts): void g5(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 nodiscard constexpr T max(T x, T y) noexcept { return x requires totally_ordered nodiscard constexpr T max(T x, T y) noexcept { return x template constexpr T PI = T{3.141592653589793238462643383L}; // (Almost) from std::numbers::pi 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 (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 char s might be declared: Array myArray; 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 <> nodiscard constexpr const char* max(const char* a, const char* b) noexcept { // Normally, the result of a direct comparison // between two C strings is undefined behaviour; // using std::strcmp makes defined. return std::strcmp(a, b) > 0 ? a : b; } using std::format_string; using std::ofstream; enum class Level { ... }; ofstream logFile{"logfile.txt"}; template void log(const format_string & fmt, Args&&... args) { std::println(logFile, fmt, 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. 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 . This allows, for example, StringHashMap to be used as shorthand for std::unordered_map . using String = std::string; // allowing optional specialization of hash functions, allocators, etc. template , typename Alloc = std::allocator > > using TreeMap = std::map ; template , 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 = HashMap template using StringHashMap = HashMap ; StringHashMap myMap = { {"Apple", 5}, {"Banana", 6}, }; Since C++20, templates can be constrained similarly to generics wildcards in Java, Go interfaces, 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 uses std::derived_from as an upper inheritance bound. 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::derived_from; using std::vector; class Player { // ... }; // T is required to be a type whose inheritance upper bound is Player, // blocking any type that does not inherit from Player template T> void processListOfPlayers(const vector & players) { // ... } Concepts can be used to implement a form of type-safe variadic parameters. For example, the Java signature void fn(T... args); using std::same_as; template void fn(same_as auto... args) { // ... } Furthermore, to constrain these to any specific type, the std::same_as and std::convertible_to concepts may be used. For instance, the Java signatures void foo(int... args); and void bar(String... args); could be written as void foo(same_as auto... args); and void bar(convertible_to auto... args); respectively. 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. For example (in C++03): : include static void trace() { std::cout T min(const T& x, const T& y); int main() { trace(); std::cout : include static void trace() { std::cout T min(const T& x, const T& y) { trace(); return a With the introduction of modules in C++20, the keyword export was re-purposed to mean exporting a symbol as accessible from an imported module. 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. In C++26 reflection, the template keyword must be used when splicing a std::meta::info to designate a template in source code. using std::meta::info; template struct Length { static constexpr size_t SIZE = N; }; constexpr info clazz = ^^Length; constexpr size_t lengthOfInterest = template [:clazz:] ::SIZE; // Induction template struct Factorial { static constexpr uint64_t VALUE = N * Factorial ::VALUE; }; // Base case via template specialization: template <> struct Factorial { static constexpr uint64_t VALUE = 1; }; With these definitions, one can compute, say 6! at compile time using the expression Factorial ::VALUE . Alternatively, constexpr since C++11, and if constexpr since C++17 can be used to calculate such values directly using a function at compile-time: template nodiscard constexpr uint64_t factorial() noexcept { if constexpr (N (); } } Because of this, template meta-programming is now mostly used to do operations on types.
Text derived from https://en.wikipedia.org/w/index.php?oldid=1376119257 under CC BY-SA 4.0; modifications have been made.