In C++17 and later, structured bindings allow you to unpack tuples and pairs nicely. However, when you have a container of pairs where the second element is itself a tuple, you cannot directly do nested structured bindings in the for loop like this:
for (auto [voxPos, [firstVec, secondVec, number]] : voxels) { ... }
This syntax is not valid in C++.
Why?
Structured bindings only unpack one level of structure at a time. The second element of your pair is a tuple, but you cannot directly unpack it inside the same structured binding declaration.
How to do it correctly?
You have two main options:
Option 1: Unpack in two steps inside the loop body
for (auto& [voxPos, voxValue] : voxels) {
auto& [firstVec, secondVec, number] = voxValue;
// Now you can use firstVec, secondVec, number directly
firstVec = firstVec.add3d(diff);
}
Note: Use auto& if you want to modify the elements in place.
Option 2: Use a helper std::tie or std::get inside the loop
for (auto& [voxPos, voxValue] : voxels) {
auto& firstVec = std::get<0>(voxValue);
auto& secondVec = std::get<1>(voxValue);
auto& number = std::get<2>(voxValue);
firstVec = firstVec.add3d(diff);
}
Summary
- Nested structured bindings in the
for loop header are not allowed.
- Unpack the outer pair in the loop header, then unpack the inner tuple inside the loop body.
- Use references (
auto&) if you want to modify the elements.
If you want, I can help you rewrite your code snippet with the correct syntax!