Comment by maccard
6 hours ago
> E.g. if you have a list finding function that returns X?, then if you give it a list of MyObject?, you don't know if you found a null element or if you found nothing.
This is a problem with the signature of the function in the first place. If it's:
template <typename T>
T* FindObject(ListType<T> items, std::function<bool(const T&)> predicate)
Whether T is MyObject or MyObject?, you're still using nullpointers as a sentinel value;
MyObject* Result = FindObject(items, predicate);
The solution is for FindObject to return a result type;
template <typename T>
Result<T&> FindObject(ListType<T> items, std::function<bool(const T&)> predicate)
where the _result_ is responsible for the return value wrapping. Making this not copy is a more advanced exercise that is bordering on impossible (safely) in C++, but Rust and newer languages have no excuse for it
No comments yet
Contribute on Hacker News ↗