3 ms·
I've been looking for something similar for C++ for a while now, after getting fed up with yet another prototype like bool OpenFile( const std::string& pat
by stinos 11y ago
I've been looking for something similar for C++ for a while now, after getting fed up with yet another prototype like
bool OpenFile( const std::string& path, File& f, std::string& err )
or similar, you get the point. At the moment I'm using a class like llvm's ErroOr<T> [1] and I'm loving it so far. The aformentioned function would be written as
ErrorOr<File> OpenFile( const std::string& path )
and contain an std::error_code if opening failed, or else a File instance.
[1] http://www.llvm.org/docs/doxygen/html/classllvm_1_1ErrorOr.html http://www.llvm.org/docs/doxygen/html/classllvm_1_1ErrorOr.h...
- vvanders 11y agoYup, this is exactly like Rust's Result<T,E>(with E being std::error_code).
- lorenzhs 11y agoThat's a very useful pattern, functional languages often call it the maybe monad. I wish more people used it in other languages. This is my version of it: https://github.com/lorenzhs/algen-framework/blob/master/common/maybe.h https://github.com/lorenzhs/algen-framework/blob/master/comm...
- stinos 11y agoThat's actually std::optional, minus the nothing/just notation? Indeed more people should use things like this. Reminds me of a similar concept I also have wrappers for: instead of manually having to compare the results of std::find etc against range.end() all over the place, the result is basically in a small container which has both the iterator returned and the end of the range. So I write const auto result = alg::find( range, pred ); if( result ) doStuff( *result ); //*result is reference to found element instead of typcial const auto end = range.cend(); const auto result = std::find( range.cbegin(), end, pred ); if( result != end ) doStuff( *result ); Not that much of a gain, but once used to it I could never go back. And I realize now this could actually just be rewritten using your maybe class or std::optional.
- lorenzhs 11y agoYeah it's pretty much std::optional but unfortunately that's in the library fundamentals TS and still in the experimental namespace last I checked. But I have to say that I prefer the name "maybe", it does convey the notion that you have to check whether it's valid much better than "optional" in my opinion.