可選作為返回值
std::optional<float> divide(float a, float b) {
if (b!=0.f) return a/b;
return {};
}
這裡我們返回分數 a/b
,但是如果沒有定義(將是無窮大),我們返回空的可選項。
一個更復雜的案例:
template<class Range, class Pred>
auto find_if( Range&& r, Pred&& p ) {
using std::begin; using std::end;
auto b = begin(r), e = end(r);
auto r = std::find_if(b, e , p );
using iterator = decltype(r);
if (r==e)
return std::optional<iterator>();
return std::optional<iterator>(r);
}
template<class Range, class T>
auto find( Range&& r, T const& t ) {
return find_if( std::forward<Range>(r), [&t](auto&& x){return x==t;} );
}
find( some_range, 7 )
在容器或範圍 some_range
中搜尋等於 7
的數字。find_if
用謂詞來做。
如果找不到,則返回空的可選項,如果是,則返回包含迭代器的可選元素。
這允許你這樣做:
if (find( vec, 7 )) {
// code
}
甚至
if (auto oit = find( vec, 7 )) {
vec.erase(*oit);
}
無需亂搞開始/結束迭代器和測試。