基于范围的for循环表达式中的临时可选项

时间:2016-06-04 23:13:17

标签: c++ std c++17 boost-optional

假设我们有一个返回std::optional<A>的函数。那么在基于范围的for循环中使用结果的正确方法是什么?最简单的方法不起作用:

for (auto&& e : a().value()) {
                   // ^--- A&& is returned, so A is destructed
                   // before loop starts

如果我们有T optional::value() &&而不是T&& optional::value() &&,则此问题不存在,但STL和Boost都以第二种方式定义它。

处理这种情况的正确方法是什么?我不喜欢我能想到的两种解决方案(sandbox):

std::experimental::optional<A> a() {
  // ...
}

void ok1() {
  // ugly if type of A is huge
  for (auto&& e : A(a().value())) {
     // ...
  }
}

void ok2() {
  // extra variable is not used
  // if for some reason we are sure that we have a value
  // and we skip checks
  auto&& b = a();
  for (auto&& e : b.value()) {
    // ...
  }
}

// it may be that the best choice is to define
A aForced() {
    return A(a().value());
}

1 个答案:

答案 0 :(得分:2)

这解决了您的问题:

template<class T>
std::decay_t<T> copy_of(T&& t){
  return std::forward<T>(t);
}

template<class T, std::size_t N>
void copy_of(T(&)[N])=delete;

然后:

for(auto&& x:copy_of(a().value()))

copy_of技术通常解决返回在for(:)循环上使用的右值引用的函数。

另一种方法是编写value_or_run(T&&, F&&f),它取一个lambda也很有用。在F中,您可以执行任何操作,例如throw,并返回T而不是T&&

同样,value_or

我个人optional使用了value_or的emplace语法 - 如果您使用的语法具有该语法,那么.value_or( throw_if_empty{} ),其中throw_if_emptyoperator T()抛出可选的空错误。