を返す関数があるとします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 の両方が 2 番目の方法で定義しています。
この状況を処理する適切な方法は何ですか? 私が考えることができる両方のソリューションが好きではありません(サンドボックス):
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());
}