structured bindings - Can I write `while(auto p = getOptionalPair())` any smarter in modern C++? - Stack Overflow

admin2025-04-17  2

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 badges84 silver badges145 bronze badges 3
  • 4 Any way you can add iterator support to whatever getNextValue fronts and use a range-based for loop? – user4581301 Commented Jan 30 at 23:25
  • Can you use monads? – Eljay Commented Jan 31 at 0:09
  • @Eljay isn't an optional already a monad? – Felix Dombek Commented Jan 31 at 23:41
Add a comment  | 

1 Answer 1

Reset to default 6

In 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).

转载请注明原文地址:http://anycun.com/QandA/1744886358a89020.html