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 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 <syntaxhighlight lang="cpp"> template <int length> Vector<length>& Vector<length>::operator+=(const Vector<length>& rhs) { for (int i = 0; i < length; ++i) value[i] += rhs.value[i]; return *this; } </syntaxhighlight> When the compiler instantiates the function template defined above, the following code may be produced:{{citation needed|date=October 2015}} <syntaxhighlight lang="cpp"> template <> Vector<2>& Vector<2>::operator+=(const Vector<2>& rhs) { value[0] += rhs.value[0]; value[1] += rhs.value[1]; return *this; } </syntaxhighlight> The compiler's optimizer should be able to unroll the <code>for</code> loop because the template parameter <code>length</code> 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.
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)