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

Christian Kühnel via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 28 05:30:16 PDT 2021


kuhnel updated this revision to Diff 354855.
kuhnel added a comment.

undo of auto formatting


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,49 @@
 /// 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 return type:
+///
+///   @code{.cpp}
+///     Expected<int> myDivide(int A, int B) {
+///       if (B == 0) {
+///         // return an Error
+///         return error("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 (!Result) {
+///       auto Error = Result.takeError();
+///       // handle the error case here
+///     } else {
+///       // handle good case here
+///     }
+///
+///   @endcode
+///
+///  Unit-testing a function returning an 'Expceted<T>':
+///   @code{.cpp}
+///   TEST(MyTests, ExpectedDemo) {
+///     auto Passed = myDivide(10, 5);
+///     // check this call has passed, this also prints the error message
+///     // if the function returns an Error
+///     ASSERT_TRUE((bool)Passed) << llvm::toString(Passed.takeError());
+///     // checked the returned value
+///     ASSERT_EQ(2, *Passed);
+///
+///     auto Failed = myDivide(1, 0);
+///     ASSERT_FALSE((bool)Failed);
+///     // make sure Failed.takeError() does not get remove by the optimizer
+///     std::cout << "Expected failure: " << llvm::toString(Failed.takeError());
+///   }
+///   @endcode
+
 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.354855.patch
Type: text/x-patch
Size: 1889 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210628/686178cb/attachment.bin>


More information about the llvm-commits mailing list