HOME

TheInfoList



OR:

Template metaprogramming (TMP) is a
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 ...
technique in which templates are used by a
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
to generate temporary
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the ...
, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants,
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, ...
s, and complete functions. The use of templates can be thought of as
compile-time polymorphism In computing, static dispatch is a form of polymorphism fully resolved during compile time. It is a form of ''method dispatch,'' which describes how a language or environment will select which implementation of a method or function to use. E ...
. The technique is used by a number of languages, the best-known being C++, but also
Curl cURL (pronounced like "curl", UK: , US: ) is a computer software project providing a library (libcurl) and command-line tool (curl) for transferring data using various network protocols. The name stands for "Client URL". History cURL was ...
, D, Nim, and XL. Template metaprogramming was, in a sense, discovered accidentally. Some other languages support similar, if not more powerful, compile-time facilities (such as
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
macros), but those are outside the scope of this article.


Components of template metaprogramming

The use of templates as a metaprogramming technique requires two distinct operations: a template must be defined, and a defined template must be instantiated. The template definition describes the generic form of the generated source code, and the instantiation causes a specific set of source code to be generated from the generic form in the template. Template metaprogramming is
Turing-complete In computability theory, a system of data-manipulation rules (such as a computer's instruction set, a programming language, or a cellular automaton) is said to be Turing-complete or computationally universal if it can be used to simulate any ...
, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram. Templates are different from '' macros''. A macro is a piece of code that executes at compile time and either performs textual manipulation of code to-be compiled (e.g. C++ macros) or manipulates the
abstract syntax tree In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurr ...
being produced by the compiler (e.g.
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...
or
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
macros). Textual macros are notably more independent of the syntax of the language being manipulated, as they merely change the in-memory text of the source code right before compilation. Template metaprograms have no mutable variables— that is, no variable can change value once it has been initialized, therefore template metaprogramming can be seen as a form of
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions tha ...
. In fact many template implementations implement flow control only through
recursion Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematic ...
, as seen in the example below.


Using template metaprogramming

Though the syntax of template metaprogramming is usually very different from the programming language it is used with, it has practical uses. Some common reasons to use templates are to implement generic programming (avoiding sections of code which are similar except for some minor variations) or to perform automatic compile-time optimization such as doing something once at compile time rather than every time the program is run — for instance, by having the compiler unroll loops to eliminate jumps and loop count decrements whenever the program is executed.


Compile-time class generation

What exactly "programming at compile-time" means can be illustrated with an example of a factorial function, which in non-template C++ can be written using recursion as follows: unsigned factorial(unsigned n) // Usage examples: // factorial(0) would yield 1; // factorial(4) would yield 24. The code above will execute at run time to determine the factorial value of the literals 0 and 4. By using template metaprogramming and template specialization to provide the ending condition for the recursion, the factorials used in the program—ignoring any factorial not used—can be calculated at compile time by this code: template struct factorial ; template <> struct factorial<0> ; // Usage examples: // factorial<0>::value would yield 1; // factorial<4>::value would yield 24. The code above calculates the factorial value of the literals 0 and 4 at compile time and uses the results as if they were precalculated constants. To be able to use templates in this manner, the compiler must know the value of its parameters at compile time, which has the natural precondition that factorial::value can only be used if X is known at compile time. In other words, X must be a constant literal or a constant expression. In
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
and
C++20 C20 or C-20 may refer to: Science and technology * Carbon-20 (C-20 or 20C), an isotope of carbon * C20, the smallest possible fullerene (a carbon molecule) * C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per sq ...
,
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 ...
and consteval were introduced to let the compiler execute code. Using constexpr and consteval, one can use the usual recursive factorial definition with the non-templated syntax.


Compile-time code optimization

The factorial example above is one example of compile-time code optimization in that all factorials used by the program are pre-compiled and injected as numeric constants at compilation, saving both run-time overhead and memory footprint. It is, however, a relatively minor optimization. As another, more significant, example of compile-time loop unrolling, template metaprogramming can be used to create length-''n'' vector classes (where ''n'' is known at compile time). The benefit over a more traditional length-''n'' vector is that the loops can be unrolled, resulting in very optimized code. As an example, consider the addition operator. A length-''n'' vector addition might be written as template Vector& Vector::operator+=(const Vector& rhs) When the compiler instantiates the function template defined above, the following code may be produced: template <> Vector<2>& Vector<2>::operator+=(const Vector<2>& rhs) The compiler's optimizer should be able to unroll the for loop because the template parameter length is a constant at compile time. However, take care and exercise caution as this may cause code bloat as separate unrolled code will be generated for each 'N'(vector size) you instantiate with.


Static polymorphism

Polymorphism is a common standard programming facility where derived objects can be used as instances of their base object but where the derived objects' methods will be invoked, as in this code class Base ; class Derived : public Base ; int main() where all invocations of virtual methods will be those of the most-derived class. This ''dynamically polymorphic'' behaviour is (typically) obtained by the creation of virtual look-up tables for classes with virtual methods, tables that are traversed at run time to identify the method to be invoked. Thus, ''run-time polymorphism'' necessarily entails execution overhead (though on modern architectures the overhead is small). However, in many cases the polymorphic behaviour needed is invariant and can be determined at compile time. Then the
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 ...
(CRTP) can be used to achieve static polymorphism, which is an imitation of polymorphism in programming code but which is resolved at compile time and thus does away with run-time virtual-table lookups. For example: template struct base ; struct derived : base ; Here the base class template will take advantage of the fact that member function bodies are not instantiated until after their declarations, and it will use members of the derived class within its own member functions, via the use of a static_cast, thus at compilation generating an object composition with polymorphic characteristics. As an example of real-world usage, the CRTP is used in the Boost iterator library. Another similar use is the " Barton–Nackman trick", sometimes referred to as "restricted template expansion", where common functionality can be placed in a base class that is used not as a contract but as a necessary component to enforce conformant behaviour while minimising code redundancy.


Static Table Generation

The benefit of static tables is the replacement of "expensive" calculations with a simple array indexing operation (for examples, see
lookup table In computer science, a lookup table (LUT) is an array that replaces runtime computation with a simpler array indexing operation. The process is termed as "direct addressing" and LUTs differ from hash tables in a way that, to retrieve a value v w ...
). In C++, there exists more than one way to generate a static table at compile time. The following listing shows an example of creating a very simple table by using recursive structs and variadic templates. The table has a size of ten. Each value is the square of the index. #include #include constexpr int TABLE_SIZE = 10; /** * Variadic template for a recursive helper struct. */ template struct Helper : Helper ; /** * Specialization of the template to end the recursion when the table size reaches TABLE_SIZE. */ template struct Helper ; constexpr std::array table = Helper<>::table; enum ; int main() The idea behind this is that the struct Helper recursively inherits from a struct with one more template argument (in this example calculated as INDEX * INDEX) until the specialization of the template ends the recursion at a size of 10 elements. The specialization simply uses the variable argument list as elements for the array. The compiler will produce code similar to the following (taken from clang called with -Xclang -ast-print -fsyntax-only). template struct Helper : Helper ; template<> struct Helper<0, <>> : Helper<0 + 1, 0 * 0> ; template<> struct Helper<1, <0>> : Helper<1 + 1, 0, 1 * 1> ; template<> struct Helper<2, <0, 1>> : Helper<2 + 1, 0, 1, 2 * 2> ; template<> struct Helper<3, <0, 1, 4>> : Helper<3 + 1, 0, 1, 4, 3 * 3> ; template<> struct Helper<4, <0, 1, 4, 9>> : Helper<4 + 1, 0, 1, 4, 9, 4 * 4> ; template<> struct Helper<5, <0, 1, 4, 9, 16>> : Helper<5 + 1, 0, 1, 4, 9, 16, 5 * 5> ; template<> struct Helper<6, <0, 1, 4, 9, 16, 25>> : Helper<6 + 1, 0, 1, 4, 9, 16, 25, 6 * 6> ; template<> struct Helper<7, <0, 1, 4, 9, 16, 25, 36>> : Helper<7 + 1, 0, 1, 4, 9, 16, 25, 36, 7 * 7> ; template<> struct Helper<8, <0, 1, 4, 9, 16, 25, 36, 49>> : Helper<8 + 1, 0, 1, 4, 9, 16, 25, 36, 49, 8 * 8> ; template<> struct Helper<9, <0, 1, 4, 9, 16, 25, 36, 49, 64>> : Helper<9 + 1, 0, 1, 4, 9, 16, 25, 36, 49, 64, 9 * 9> ; template<> struct Helper<10, <0, 1, 4, 9, 16, 25, 36, 49, 64, 81>> ; Since C++17 this can be more readably written as: #include #include constexpr int TABLE_SIZE = 10; constexpr std::array table = [] (); enum ; int main() To show a more sophisticated example the code in the following listing has been extended to have a helper for value calculation (in preparation for more complicated computations), a table specific offset and a template argument for the type of the table values (e.g. uint8_t, uint16_t, ...). #include #include constexpr int TABLE_SIZE = 20; constexpr int OFFSET = 12; /** * Template to calculate a single table entry */ template struct ValueHelper ; /** * Variadic template for a recursive helper struct. */ template struct Helper : Helper::value> ; /** * Specialization of the template to end the recursion when the table size reaches TABLE_SIZE. */ template struct Helper ; constexpr std::array table = Helper::table; int main() Which could be written as follows using C++17: #include #include constexpr int TABLE_SIZE = 20; constexpr int OFFSET = 12; template constexpr std::array table = [] (); int main()


Concepts

The C++20 standard brought C++ programmers a new tool for meta template programming, concepts.
Concepts Concepts are defined as abstract ideas. They are understood to be the fundamental building blocks of the concept behind principles, thoughts and beliefs. They play an important role in all aspects of cognition. As such, concepts are studied by s ...
allow programmers to specify requirements for the type, to make instantiation of template possible. The compiler looks for a template with the concept that has the highest requirements. Here is an example of the famous
Fizz buzz Fizz buzz is a group word game for children to teach them about division (mathematics), division. Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the wor ...
problem solved with Template Meta Programming. #include // for pretty printing of types #include #include /** * Type representation of words to print */ struct Fizz ; struct Buzz ; struct FizzBuzz ; template struct number ; /** * Concepts used to define condition for specializations */ template concept has_N = requires; template concept fizz_c = has_N && requires; template concept buzz_c = has_N && requires; template concept fizzbuzz_c = fizz_c && buzz_c; /** * By specializing `res` structure, with concepts requirements, proper instantiation is performed */ template struct res; template struct res ; template struct res ; template struct res ; template struct res ; /** * Predeclaration of concatenator */ template struct concatenator; /** * Recursive way of concatenating next types */ template struct concatenator> ; /** * Base case */ template struct concatenator<0, std::tuple> ; /** * Final result getter */ template using fizz_buzz_full_template = typename concatenator>::result>>::type; int main()


Benefits and drawbacks of template metaprogramming

; Compile-time versus execution-time tradeoff : If a great deal of template metaprogramming is used. ;
Generic programming : Template metaprogramming allows the programmer to focus on architecture and delegate to the compiler the generation of any implementation required by client code. Thus, template metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability. ; Readability : With respect to C++ prior to C++11, the syntax and idioms of template metaprogramming were esoteric compared to conventional C++ programming, and template metaprograms could be very difficult to understand. But from C++11 onward the syntax for value computation metaprogramming becomes more and more akin to "normal" C++, with less and less readability penalty.


See also

* Substitution failure is not an error (SFINAE) *
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 ...
*
Preprocessor In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input in another program. The output is said to be a preprocessed form of the input data, which is often used by so ...
*
Parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
* Expression templates * Variadic Templates *
Compile-time function execution In computing, compile-time function execution (or compile time function evaluation, or general constant expressions) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the ...


References

* * * * *


External links

* * (built using template-metaprogramming) * (use STL algorithms easily) * * (type-safe metaprogramming in Haskell) * (template metaprogramming in the D programming language) * * * * * * {{cite web , url = http://www.intelib.org/intro.html , title = A library for LISP-style programming in C++ Metaprogramming C++ Articles with example C++ code