std::optional as return value
suggest changestd::optional is a C++17 type.
std::optional<float> divide(float a, float b) {
if (b!=0.f) return a/b;
return {};
}
Here we return the fraction a/b, or an empty optional when b is zero. That empty result is a chosen sentinel. Floating-point division by zero is not required to produce infinity.
A more complex case:
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 found = std::find_if(b, e , p );
using iterator = decltype(found);
if (found==e)
return std::optional<iterator>();
return std::optional<iterator>(found);
}
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 ) searches the container or range some_range for something equal to the number 7. find_if does it with a predicate.
It returns either an empty optional if it was not found, or an optional containing an iterator to the element if it was.
This allows you to do:
if (find( vec, 7 )) {
// code
}
or even
if (auto oit = find( vec, 7 )) {
vec.erase(*oit);
}
without having to mess around with begin/end iterators and tests.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents