How to do it...

It might be handy (and it actually is) to avoid explicitly specifying the type of variable that will be used, especially when it is particularly long and used very locally:

  1. Let's start with a typical example: 
std::map<int, std::string> payslips;
// ...
for (std::map<int,
std::string>::const_iterator iter = payslips.begin();
iter !=payslips.end(); ++iter)
{
// ...
}
  1. Now, let's rewrite it with auto:
std::map<int, std::string> payslips;
// ...
for (auto iter = payslips.begin(); iter !=payslips.end(); ++iter)
{
// ...
}
  1. Let's look at another example:
auto speed = 123;         // speed is an int
auto height = calculate (); // height will be of the
// type returned by calculate()

decltype() is another mechanism offered by C++ that can deduce the type of expression when the expression is more complex than the auto case.

  1. Let's look at this using an example: 
decltype(a) y = x + 1;  // deducing the type of a
decltype(str->x) y; // deducing the type of str->x, where str is
// a struct and x
// an int element of that struct

Could we use auto instead of decltype() in these two examples? We'll take a look in the next section.