Content deleted Content added
→Benefits and drawbacks of template metaprogramming: what standard? when? for what language? |
Rescuing 2 sources and tagging 0 as dead.) #IABot (v2.0.9.5 |
||
(35 intermediate revisions by 28 users not shown) | |||
Line 1:
{{Short description|Metaprogramming technique}}
{{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
Template metaprogramming was, in a sense, discovered accidentally.<ref name="Meyers2005">{{cite book|author=Scott Meyers|title=Effective C++: 55 Specific Ways to Improve Your Programs and Designs|url=https://books.google.com/books?id=Qx5oyB49poYC
Some other languages support similar, if not more powerful, compile-time facilities (such as [[Lisp (programming language)|Lisp]] [[Macro (computer science)#Syntactic macros|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 [[Instance (computer science)|instantiated]]. The
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
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.
Template metaprograms have no [[Immutable object|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 fact many template implementations implement flow control only through [[Recursion (computer science)|recursion]], as seen in the example below.
Line 23:
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:
<syntaxhighlight lang=cpp>
unsigned
return n == 0 ? 1 : n * factorial(n - 1);
}
Line 31:
// factorial(4) would yield 24.
</syntaxhighlight>
The code above will execute at run time to determine the factorial value of the literals
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:
<syntaxhighlight lang=cpp>
template <unsigned
struct factorial {
};
template <>
struct factorial<0> {
};
Line 48:
// factorial<4>::value would yield 24.
</syntaxhighlight>
The code above calculates the factorial value of the literals
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>
==Compile-time code optimization==
{{see also|Compile
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 131:
};
</syntaxhighlight>
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 <code>static_cast</code>, thus at compilation generating an object composition with polymorphic characteristics. As an example of real-world usage, the CRTP is used in the [[Boost library|Boost]] [[iterator]] library.<ref>{{Cite web|url=http://www.boost.org/libs/iterator/doc/iterator_facade.html|title = Iterator Facade - 1.79.0}}</ref>
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.
Line 167:
int main() {
for (int i=0; i < TABLE_SIZE; i++) {
std::cout << table[i] << std::endl; // run time use
}
Line 224:
int main() {
for (int i=0; i < TABLE_SIZE; i++) {
std::cout << table[i] << std::endl; // run time use
}
std::cout << "FOUR: " << FOUR << std::endl;
}
</syntaxhighlight>
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, ...).
Line 265:
int main() {
for (int i = 0; i < TABLE_SIZE; i++) {
std::cout << table[i] << std::endl;
}
Line 278:
constexpr int OFFSET = 12;
template<typename VALUETYPE,
constexpr std::array<VALUETYPE, TABLE_SIZE> table = [] { // OR: constexpr auto table
std::array<VALUETYPE, TABLE_SIZE> A = {};
Line 288:
int main() {
for (int i = 0; i < TABLE_SIZE; i++) {
std::cout << table<uint16_t, OFFSET>[i] << std::endl;
}
}
</syntaxhighlight>
==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.
Here is an example of the famous [[Fizz buzz]] problem solved with Template Meta Programming.
<syntaxhighlight lang="cpp">
#include <boost/type_index.hpp> // for pretty printing of types
#include <iostream>
#include <tuple>
/**
* Type representation of words to print
*/
struct Fizz {};
struct Buzz {};
struct FizzBuzz {};
template<size_t _N> struct number { constexpr static size_t N = _N; };
/**
* Concepts used to define condition for specializations
*/
template<typename Any> concept has_N = requires{ requires Any::N - Any::N == 0; };
template<typename A> concept fizz_c = has_N<A> && requires{ requires A::N % 3 == 0; };
template<typename A> concept buzz_c = has_N<A> && requires{ requires A::N % 5 == 0;};
template<typename A> concept fizzbuzz_c = fizz_c<A> && buzz_c<A>;
/**
* By specializing `res` structure, with concepts requirements, proper instantiation is performed
*/
template<typename X> struct res;
template<fizzbuzz_c X> struct res<X> { using result = FizzBuzz; };
template<fizz_c X> struct res<X> { using result = Fizz; };
template<buzz_c X> struct res<X> { using result = Buzz; };
template<has_N X> struct res<X> { using result = X; };
/**
* Predeclaration of concatenator
*/
template <size_t cnt, typename... Args>
struct concatenator;
/**
* Recursive way of concatenating next types
*/
template <size_t cnt, typename ... Args>
struct concatenator<cnt, std::tuple<Args...>>
{ using type = typename concatenator<cnt - 1, std::tuple< typename res< number<cnt> >::result, Args... >>::type;};
/**
* Base case
*/
template <typename... Args> struct concatenator<0, std::tuple<Args...>> { using type = std::tuple<Args...>;};
/**
* Final result getter
*/
template<size_t Amount>
using fizz_buzz_full_template = typename concatenator<Amount - 1, std::tuple<typename res<number<Amount>>::result>>::type;
int main()
{
// printing result with boost, so it's clear
std::cout << boost::typeindex::type_id<fizz_buzz_full_template<100>>().pretty_name() << std::endl;
/*
Result:
std::tuple<number<1ul>, number<2ul>, Fizz, number<4ul>, Buzz, Fizz, number<7ul>, number<8ul>, Fizz, Buzz, number<11ul>, Fizz, number<13ul>, number<14ul>, FizzBuzz, number<16ul>, number<17ul>, Fizz, number<19ul>, Buzz, Fizz, number<22ul>, number<23ul>, Fizz, Buzz, number<26ul>, Fizz, number<28ul>, number<29ul>, FizzBuzz, number<31ul>, number<32ul>, Fizz, number<34ul>, Buzz, Fizz, number<37ul>, number<38ul>, Fizz, Buzz, number<41ul>, Fizz, number<43ul>, number<44ul>, FizzBuzz, number<46ul>, number<47ul>, Fizz, number<49ul>, Buzz, Fizz, number<52ul>, number<53ul>, Fizz, Buzz, number<56ul>, Fizz, number<58ul>, number<59ul>, FizzBuzz, number<61ul>, number<62ul>, Fizz, number<64ul>, Buzz, Fizz, number<67ul>, number<68ul>, Fizz, Buzz, number<71ul>, Fizz, number<73ul>, number<74ul>, FizzBuzz, number<76ul>, number<77ul>, Fizz, number<79ul>, Buzz, Fizz, number<82ul>, number<83ul>, Fizz, Buzz, number<86ul>, Fizz, number<88ul>, number<89ul>, FizzBuzz, number<91ul>, number<92ul>, Fizz, number<94ul>, Buzz, Fizz, number<97ul>, number<98ul>, Fizz, Buzz>
*/
}
</syntaxhighlight>
==Benefits and drawbacks of template metaprogramming==
| first1 = K.
| last1 = Czarnecki
Line 312 ⟶ 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
| first1 = Tim
| last1 = Sheard
Line 324 ⟶ 396:
| quote = ''Robinson’s provocative paper identifies C++ templates as a major, albeit accidental, success of the C++ language design. Despite the extremely baroque nature of template meta-programming, templates are used in fascinating ways that extend beyond the wildest dreams of the language designers. Perhaps surprisingly, in view of the fact that templates are functional programs, functional programmers have been slow to capitalize on C++’s success''
| ref = Sheard, S.P.Jones - Template Meta-programming for Haskell
}}</ref> 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==
Line 332 ⟶ 404:
* [[Parametric polymorphism]]
* [[Expression templates]]
* [[Variadic
* [[Compile
==References==
Line 339 ⟶ 411:
* {{cite book | authorlink = Ulrich W. Eisenecker | first = Ulrich W. | last = Eisenecker | title = Generative Programming: Methods, Tools, and Applications | publisher = Addison-Wesley | isbn = 0-201-30977-7 | year = 2000 }}
* {{cite book | authorlink = Andrei Alexandrescu | first = Andrei | last = Alexandrescu | title = Modern C++ Design: Generic Programming and Design Patterns Applied | publisher = Addison-Wesley | isbn = 3-8266-1347-3 | year = 2003 }}
* {{cite book | authorlink1 = David Abrahams (computer programmer) |
* {{cite book | authorlink1 = David
* {{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 350 ⟶ 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
* {{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]]
|