[PATCH] D105014: added some example code for llvm::Expected<T>

Christian Kühnel via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Jun 30 01:30:16 PDT 2021


kuhnel updated this revision to Diff 355472.
kuhnel marked an inline comment as done.
kuhnel added a comment.

argh, again fixed autoformatter :(


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105014/new/

https://reviews.llvm.org/D105014

Files:
  llvm/include/llvm/Support/Error.h


Index: llvm/include/llvm/Support/Error.h
===================================================================
--- llvm/include/llvm/Support/Error.h
+++ llvm/include/llvm/Support/Error.h
@@ -436,6 +436,40 @@
 /// Error cannot be copied, this class replaces getError() with
 /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
 /// error class type.
+///
+/// Example usage of 'Expected<T>' as a function return type:
+///
+///   @code{.cpp}
+///     Expected<int> myDivide(int A, int B) {
+///       if (B == 0) {
+///         // return an Error
+///         return createStringError(inconvertibleErrorCode(),
+///                                  "B must not be zero!");
+///       }
+///       // return an integer
+///       return A / B;
+///     }
+///   @endcode
+///
+///   Checking the results of to a function returning 'Expected<T>':
+///   @code{.cpp}
+///     auto Result = myDivide(X,Y);
+///     if (auto E = Result.takeError()) {
+///        // We must consume the error. Typically one of:
+///        // - return the error to our caller
+///        // - toString(), when logging
+///        // - consumeError(), to silently swallow the error
+///        // - handleErrors(), to distinguish error types
+///        errs() << "Problem with division "
+///               << toString(E) << "\n";
+///     }
+///     // use the result
+///     outs() << "The answer is " << *Result << "\n";
+///   @endcode
+///
+///  For unit-testing a function returning an 'Expceted<T>', see the
+///  'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
+
 template <class T> class LLVM_NODISCARD Expected {
   template <class T1> friend class ExpectedAsOutParameter;
   template <class OtherT> friend class Expected;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D105014.355472.patch
Type: text/x-patch
Size: 1749 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20210630/5f3b7083/attachment-0001.bin>


More information about the cfe-commits mailing list