Timo
Timo

Reputation: 9835

Are nested structured bindings possible?

Assume I have an object of type

std::map<std::string, std::tuple<int, float>> data;

Is it possible to access the element types in a nested way (i.e. when used in ranged for loop) like this

for (auto [str, [my_int, my_float]] : data) /* do something */

Upvotes: 85

Views: 12646

Answers (3)

Kitiara
Kitiara

Reputation: 498

You can do the following in C++20

for (auto& [my_int, my_float] : data | std::views::values)
{
    // Some code
}

Upvotes: 4

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

No, they aren't possible; but this is:

for (auto&& [key, value] : data) {
  auto&& [my_int, my_float] = value;
}

which is close at least.

Upvotes: 43

bolov
bolov

Reputation: 75707

No, it is not possible.

I distinctly remember reading somewhere that nested structured bindings are not allowed for C++17, but they are considering allowing it in a future standard. Can't find the source though.

Upvotes: 53

Related Questions