How it works...
The first example with auto shows that the type is deduced, at compile time, from the right-hand parameter. auto is used in simple cases.
decltype() deduces the type of expression. In the example, it defines the y variable so that it's the same type as a. As you can imagine, this would not be possible with auto. Why? This is pretty simple: decltype() tells the compiler to define a variable of a specific type; in the first example, y is a variable with the same type as a. With auto, the type is deduced automatically.
We should use auto and decltype() anytime we don't have to explicitly specify the type of a variable; for example, when we need a double type (and not a float). It's worth mentioning that both auto and decltype() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access