Search code examples
c++for-loopc++17auto

In this syntax, what is the actual type of auto?


In the C++17 for loop syntax for(auto [key, val]: students), what is auto replacing?

If students was, for example std::map<int,char*>, what would be written if not auto? I don't understand what it even is taking the place of. [int,char*]?


Solution

  • type [a,b,c] is a structured binding, and those force you to use auto (possibly decorated with const and/or &/&&).

    But aside from that, auto expands to the same type it would expand to if [...] was replaced with a variable name. In

    for (auto elem : students)
    

    ... auto expands to std::pair<const int, char *>.

    In a structured binding it expands to the same type, but the resulting "variable" of this type is unnamed.

    Then, for each name in brackets, a reference (or something similar to a reference) is introduced, that points to one of the elements of that unnamed variable.