最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论