Template metaprogramming: Difference between revisions

Content deleted Content added
No edit summary
Rescuing 2 sources and tagging 0 as dead.) #IABot (v2.0.9.5
 
(12 intermediate revisions by 11 users not shown)
Line 1:
{{Short description|Metaprogramming technique}}
{{Cleanup bare URLs|date=September 2022}}
{{More footnotes needed|date=June 2010}}
{{Programming paradigms}}
 
'''Template metaprogramming''' ('''TMP''') is a [[metaprogramming]] technique in which [[Generic programming|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 templates can include [[compile time|compile-time]] [[constant (programming)|constant]]s, [[data structure]]s, and complete [[function (computer science)|function]]s. The use of templates can be thought of as [[Compile-time function execution|compile-time polymorphism]]. The technique is used by a number of languages, the best-known being [[C++]], but also [[Curl programming language|Curl]], [[D programming language|D]], [[Nim (programming language)|Nim]], and [[XL Programming Language|XL]].
Line 12 ⟶ 11:
The use of templates as a metaprogramming technique requires two distinct operations: a template must be defined, and a defined template must be [[Instance (computer science)|instantiated]]. The generic form of the generated source code is described in the template definition, and when the template is instantiated, the generic form in the template is used to generate a specific set of source code.
 
Template metaprogramming is [[Turing-complete]], meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram.<ref name=Veldhuizen2003>{{cite documentCiteSeerX|last1=Veldhuizen|first1=Todd L.|title=C++ Templates are Turing Complete|year=2003|citeseerx=10.1.1.14.3670}}</ref>
 
Templates are different from ''[[Macro (computer science)#Programming macros|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]] being produced by the compiler (e.g. [[Rust (programming language)|Rust]] or [[Lisp (programming language)|Lisp]] 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.
Line 52 ⟶ 51:
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<X>::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]] and [[C++20]], [[constexpr]] 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.<ref>http{{Cite web|url=https://www.cprogramming.com/c++11/c++11-compile-time-processing-with-constexpr.html|title=Constexpr - Generalized Constant Expressions in C++11 - Cprogramming.com|website=www.cprogramming.com}}</ref>
 
==Compile-time code optimization==
{{see also|Compile-time function execution}}
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
Line 279 ⟶ 278:
constexpr int OFFSET = 12;
 
template<typename VALUETYPE, VALUETYPEint OFFSET>
constexpr std::array<VALUETYPE, TABLE_SIZE> table = [] { // OR: constexpr auto table
std::array<VALUETYPE, TABLE_SIZE> A = {};
Line 296 ⟶ 295:
 
==Concepts==
The C++20 standard brought C++ programmers a new tool for meta template programming, concepts.<ref>{{Cite web|url=https://en.cppreference.com/w/cpp/language/constraints|title=Constraints and concepts (since C++20) - cppreference.com|website=en.cppreference.com}}</ref>
 
[[Concepts (C++)|Concepts]] 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.
Line 368 ⟶ 367:
 
==Benefits and drawbacks of template metaprogramming==
; Compile-time versus execution-time tradeofftradeoffs get :visible Ifif 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 programming|generic code]], facilitating code minimization and better maintainability{{Citation needed|date=June 2014}}.
; Readability :* With respect to C++ prior to version ''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.<ref>{{cite documentweb
| first1 = K.
| last1 = Czarnecki
Line 385 ⟶ 384:
|quote=''C++ Template Metaprogramming suffers from a number of limitations, including portability problems due to compiler limitations (although this has significantly improved in the last few years), lack of debugging support or IO during template instantiation, long compilation times, long and incomprehensible errors, poor readability of the code, and poor error reporting.''
| ref = Czarnecki, O’Donnell, Striegnitz, Taha - DSL implementation in metaocaml, template haskell, and C++
}}</ref><ref>{{cite documentweb
| first1 = Tim
| last1 = Sheard
Line 414 ⟶ 413:
* {{cite book | authorlink1 = David Abrahams (computer programmer) | first1 = David | last1 = Abrahams | authorlink2 = Aleksey Gurtovoy | first2 = Aleksey | last2 = Gurtovoy | title = C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond | publisher = Addison-Wesley | isbn = 0-321-22725-5 | date = January 2005 }}
* {{cite book | authorlink1 = David Vandevoorde | first1 = David | last1 = Vandevoorde | authorlink2 = Nicolai M. Josuttis | first2 = Nicolai M. | last2 = Josuttis | title = C++ Templates: The Complete Guide | publisher = Addison-Wesley | isbn = 0-201-73484-2 | year = 2003 }}
* {{cite book | authorlink = Manuel Clavel | first = Manuel | last = Clavel | title = Reflection in Rewriting Logic: Metalogical Foundations and Metaprogramming Applications | isbn = 1-57586-238-7 | date = 2000-10-16 | publisher = Cambridge University Press }}
 
==External links==
Line 423 ⟶ 422:
* {{cite web | url = https://wiki.haskell.org/Template_Haskell | title = Template Haskell }} (type-safe metaprogramming in Haskell)
* {{cite web | authorlink = Walter Bright | first = Walter | last = Bright | url = http://www.digitalmars.com/d/templates-revisited.html | title = Templates Revisited }} (template metaprogramming in the [[D programming language]])
* {{cite web | url = http://staff.ustc.edu.cn/~xyfeng/teaching/FOPL/lectureNotes/MetaprogrammingCpp.pdf | title = Metaprogramming in C++ | authorlink = Johannes Koskinen | first = Johannes | last = Koskinen | access-date = 2014-06-20 | archive-date = 2014-08-28 | archive-url = https://web.archive.org/web/20140828190250/http://staff.ustc.edu.cn/~xyfeng/teaching/FOPL/lectureNotes/MetaprogrammingCpp.pdf | url-status = dead }}
* {{cite web | url = http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf | title = Reflection support by means of template metaprogramming | first1 = Giuseppe | last1 = Attardi | first2 = Antonio | last2 = Cisternino | access-date = 2008-10-24 | archive-date = 2016-03-03 | archive-url = https://web.archive.org/web/20160303183212/http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf | url-status = dead }}
* {{cite documentCiteSeerX | citeseerx = 10.1.1.14.5881 | title = Static data structures | first1 = Michael C. | last1 = Burton | first2 = William G. | last2 = Griswold | first3 = Andrew D. | last3 = McCulloch | first4 = Gary A. | last4 = Huber | year = 2002 }}
* {{cite web | url = http://www.codeproject.com/Articles/19989/Template-Meta-Programming-and-Number-Theory | title = Template Meta Programming and Number Theory | first = Zeeshan | last = Amjad | date = 13 August 2007 }}
* {{cite web | url = http://www.codeproject.com/Articles/20180/Template-Meta-Programming-and-Number-Theory-Part | title = Template Meta Programming and Number Theory: Part 2 | first = Zeeshan | last = Amjad | date = 24 August 2007 }}
* {{cite web | url = http://www.intelib.org/intro.html | title = A library for LISP-style programming in C++ }}
 
{{Programming paradigms navbox}}
 
[[Category:Metaprogramming]]