Page 6 - Human Readable Magazine v01
P. 6

  LANGUAGE FEATURES
 What are unevaluated operands in C++?
 We can now rewrite the first group of functions in a smarter way by means of this tool and using decltype as shown in the previous sections to probe (but not to evaluate!) our types and their com- pile-time properties:
How does it work? Because of the rules of the language, the first function that matches the given arguments is as follows:
Here we use decltype to probe a compile-time property for the type T. Probe, not evaluate. Therefore, we have no side effects here. SFINAE does the rest for us. In case the type T has a member h, we enter the first function. Otherwise, we receive a soft error, but the compiler continues to probe the other functions to turn it into a
The choice trick is instead widely used and combines different aspects of the language. It may seem complicated initially, but it’s really simple and allows us to solve a common problem with a very compact code.
hard error and return to us. This isn’t even an option actually be- cause of our fallback that will accept everything that doesn’t match one of the previous cases:
Another important thing that perhaps doesn’t immediately catch our attention is that there is no need to resort to the detection id- iom to test our types, which relieves us from having to write a lot of code.
Finally, we have as many functions as there are rules, something that is definitely easy to maintain and to reason on.
CONCLUSION
We have seen how the C++ language offers a few very interesting operators. Some aren’t very useful when you want to do SFINAE; others can be used within certain limits, but one in particular seems to be good enough for most of the cases: decltype.
The choice trick is instead widely used and combines different aspects of the language. It may seem complicated initially, but it’s really simple and allows us to solve a common problem with a very compact code. You’ve probably already encountered it in a simpler form, where the overload is solved by a combination of int and char, but the way it works is exactly the same. We just walked through an extended version of it.
Obviously the uses and abuses of decltype aren’t limited to this example, but I’ll leave the rest for future articles, hoping that you enjoyed what you’ve read so far.è
    18 | Human Readable Magazine
 Illustration by pikisuperstar - www.freepik.com




















































































   2   3   4   5   6