Quick summary ↬ In this short article, I have posted an example that does the reinterpret_cast on an integer and convert it to char pointer and then the value pointed by the char pointer is converted to r-value reference all in a macro.
Beautiful code #1
Beautiful code #1 explanation
Let me explain the macro first.
We have declared a macro called
CAPSY_DECLVAL which can accept any number of variables (note the
…). In the macro definition we have double
reinterpret_cast. The outcome of the far right
reinterpret_cast is converting the integer
char*. This is very dangerous conversion but that is how
reinterpret_cast works. Once it is converted to
char* the value pointed by the
char* is passed to the parent level
reinterpret_cast. The sub code is
__VA_ARGS__ has the value
int which is passed in the main function as an argument to the macro.
Let’s move one step to the left again and see that a variable
add_rvalue_ref is called that is just a
r-value reference T&&. So the interpretation in our example is
int&&. Now let’s write the whole macro after applying the template parameter as shown below:
In short, an integer converted to
char* and then the value pointed by the
char* is again converted to int&& and that is all defined inside the macro CAPSY_DECLVAL which accepts variadic parameters. Inside the main function we just print the data type of the variable we arrive at using the code
typeid(decltype(CAPSY_DECLVAL(int))).name(). Isn’t that beautiful?
I will write series of beautiful code and I hope to come up with 500 snippets of beautiful C++ code in 2023.