I am looking at some code which is
while (const auto optionalIndexedValue = getNextValue())
{
const auto& [index, value] = *optionalIndexedValue;
// use index and value
}
I have full control over the return type of getNextValue
(so could add a bool to the tuple or anything else).
Could any modern C++ features be used to achieve a syntax where the structured binding happens in the loop header?
What would in general be the nicest way to write this?
I am looking at some code which is
while (const auto optionalIndexedValue = getNextValue())
{
const auto& [index, value] = *optionalIndexedValue;
// use index and value
}
I have full control over the return type of getNextValue
(so could add a bool to the tuple or anything else).
Could any modern C++ features be used to achieve a syntax where the structured binding happens in the loop header?
What would in general be the nicest way to write this?
Share Improve this question asked Jan 30 at 23:15 Felix DombekFelix Dombek 14.4k19 gold badges83 silver badges145 bronze badges 3 |1 Answer
Reset to default 6In C++26 you can just put the structured binding declaration as the condition. The test is on the whole object, precisely because of this sort of use case.
However, note that, even though the conversion to bool
takes place first, the decomposition always occurs. The relevant consequence is that you can use this on an optional value only if you arrange for decomposition to always succeed, providing either a default value or a reference to some default object. If you wanted to be very generic, you might make that reference be to an inactive union member to avoid having a real object (and needing to know how to construct it).
getNextValue
fronts and use a range-based for loop? – user4581301 Commented Jan 30 at 23:25