user41010
user41010

Reputation: 101

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*]?

Upvotes: 1

Views: 169

Answers (2)

VLL
VLL

Reputation: 10165

The std::map is filled with std::pair<const int, char*>, so one way to write this loop would be

for (std::pair<const int, char*> pair : students)

We could also separate the pair with std::tie, but this syntax cannot be used in the loop:

int key;
char* value;
std::pair<int, char*> pair;
std::tie(key, value) = pair;

Statement auto [key, val] replaces std::tie. This syntax is called structured binding.

Upvotes: 1

HolyBlackCat
HolyBlackCat

Reputation: 96286

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.

Upvotes: 3

Related Questions