auto
and decltype
Explained,
by Thomas Becker
about me
auto
Is Not a Luxury
In the examples that we have seen so far, the use of the auto keyword is
a convenience that saves us some unnecessary thinking and typing and makes the code look
less cluttered. auto also allows us to do things that aren't possible
without it1. This happens whenever you want to declare a variable whose type is the same
as the type of some expression that involves templated variables. For example, suppose you're
writing a function template with two arguments whose precondition is that the product of the
two arguments is defined. Inside the function, you want to declare a variable to hold the
product of the two arguments:
template<typename T, typename S> void foo(T lhs, S rhs) { auto prod = lhs * rhs; //... }In standard C++ prior to C++11, this could not be done at all, because the type of the product is something that the compiler must infer every time the function template is instantiated. For example, if both lhs and rhs are int s, then
the type of the product is int . If one of the two is an int and the other
is a double , then the int gets promoted to a double , and the
type of the product is double . Infinitely many more examples are possible using
user-defined types and multiplication operators.
1Strictly speaking,
auto is never really necessary:
in theory, it can always be replaced with the more powerful decltype . For example, the line
auto prod = lhs * rhs;in the code example above could be replaced with decltype(lhs * rhs) prod = lhs * rhs;The latter is clearly less elegant than the former. Moreover, we'll see in the next few sections that the way decltype deduces the type of an expression is different from the
way auto does. If you really wanted to shun auto altogether and use decltype
instead, you'd have to account for these differences using things like remove_reference
in all the right places. That would become tedious and error-prone.
|