Search code examples
c++structured-bindings

Can I write `while(auto p = getOptionalPair())` any smarter in modern C++?


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?


Solution

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