Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Template metaprogramming
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==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: <syntaxhighlight lang=cpp> unsigned factorial(unsigned n) { return n == 0 ? 1 : n * factorial(n - 1); } // Usage examples: // factorial(0) would yield 1; // factorial(4) would yield 24. </syntaxhighlight> 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: <syntaxhighlight lang=cpp> template <unsigned N> struct factorial { static constexpr unsigned value = N * factorial<N - 1>::value; }; template <> struct factorial<0> { static constexpr unsigned value = 1; }; // Usage examples: // factorial<0>::value would yield 1; // factorial<4>::value would yield 24. </syntaxhighlight> 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<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>{{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>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)