In my last post, “Template Metaprogramming – How it All Started“, I wrote about the roots of template metaprogramming. I presented the hello world of template metaprogramming: calculating the factorial of a number at compile time. In this post, I will write about how template metaprogramming can modify types at compile time.
The factorial program in the last post, “Template Metaprogramming – How it All Started” was an excellent example but not idiomatic for template metaprogramming. Manipulating types at compile time is typical in template metaprogramming.
Type Manipulation at Compile Time
For example, here is what std::move is conceptionally doing:
std::move takes its argument
arg, deduces its type
(decltype(arg)), removes its reference (
std::remove_reverence), and casts it to an rvalue reference (
std::move is an rvalue reference cast. Now, move semantics can kick in.
How can a function remove constness from its argument?
removeConst the way
std::remove_const is probably implemented in the type-traits library.
std::is_same from the type-traits library helps me to decide at compile-time if both types are the same. In case of
removeConst<int> the primary or general class template kicks in; in case of
removeConst<const int>, the partial specialization for
const T applies. The critical observation is that both class templates return the underlying type in (1) and (2) via the alias
type. As promised, the constness of the argument is removed.
There are additional observations:
- Template specialization (partial or full) is conditional execution at compile-time. Let me be more specific: When I use
int, the compiler chooses the primary or general template. When I use a constant
int, the compiler chooses the partial specialization for
- The expression using
type = Tserves as the return value, which is, in this case, a type.
- When you study the program removeConst.cpp on C++ Insights, you see that the expression that the expression
std::is_same<int, removeConst<int>::type>::valueboils down to the boolean value
std::integral_constant<bool, true>::valuethat is displayed as
Let me step back and write about template metaprogramming for a more conceptual view.
At run time, we use data and functions. At compile time, we use metadata and metafunctions. Quite logically, it’s called meta because we do metaprogramming.
Metadata are values that metafunctions us at compile time.
There are three types of values:
- Types such as int, or double
- Non-types such as integrals, enumerators, pointers, references, and floating-points with C++20
- Templates such as
You can read more about the three types of values in my previous post, “Alias Templates and Template Parameters“.
Metafunctions are functions that are executed at compile time.
Admittedly, this sounds strange: Types are used in template metaprogramming to simulate functions. Based on the definition of metafunctions,
constexpr functions that can be executed at compile time, are also metafunctions. The same holds for
consteval functions in C++20.
Here are two metafunctions.
The first metafunction
Product returns a value, and the second one
removeConst returns a type. The name value and type are just naming conventions for the return values. If a meta-function returns a value, it is called a value; if it returns a type, it is called a type. The type-traits library follows exactly this naming convention.
It is quite enlightening to compare functions with metafunctions.
Functions versus Metafunctions
The following function
power and the metafunction
Power calculate pow(2, 10) at run time and compile time.
This is the main difference:
- Arguments: The function arguments go into the round brackets (( … )), and the metafunction arguments go into the sharp brackets (
< ...>). This observation also holds for defining the function and the meta function. The function uses round brackets and metafunction sharp brackets. Each metafunction argument produces a new type.
- Return value: The function uses a return statement, and the meta function is a static integral constant value.
I elaborate more on this comparison in the upcoming post
about constexpr and
consteval functions. Here is the output of the program.
power is executed at run time and
Power at compile time, but what is happening in the following example?
The question is obvious: Is
Power a function or a metafunction? I promise the answer to this question gives you more insight.
In my next post, I will analyze the function/metafunction
Power and introduce the type-traits library. The type traits library is idiomatic for compile-time programming in C++.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
|My special thanks to SHAVEDYAKS|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,