Real-world examples of metaprogramming
Advanced metaprogramming can appear to be very academic, so in order to demonstrate its usefulness, let's look at some examples that not only demonstrate the syntax of metaprogramming, but how it can be used in practice.
Example 1: creating a generic safe cast function
When casting between data types in C++, there is a multitude of different ways things can go wrong:
- You might lose a value if casting to an integer type of a lower bit length.
- You might lose a value if casting a negative value to an unsigned integer.
- If casting from a pointer to any other integer than
uintptr_t
, the correct address might become incorrect. This is because C++ only guarantees thatuintptr_t
is the only integer type that can withhold an address. - If casting from
double
tofloat
, the result might beint
if thedouble
value is too large forfloat
to withhold. - If casting between pointers with a
static_cast()
, we might get...