May 14, 2018

[C++][C++20] expected, borrow idea from golang

std::experimental::expected LWG design issues

Introduction to proposed std::expected - Niall Douglas - Meeting C++ 2017

Note:
When working for vmware SRM, we rarely have throw exception, instead, accumulated in a way and pop up to the caller stack.

Layout the 'expected' (no pun intended) items:

  • General: learn once use many
  • Minimize soft errors; maximize hard errors
    • Avoid metastable states
  • Allow centralized handling
    • Keep error handling out of most code
  • Allow local handling
    • Library can’t decide handling locus
  • Transport an arbitrary amount of error info
  • Demand little cost on the normal path
  • Make correct code easy to write

Today's Plan

  • + Local handling
  • + Minimize soft errors
  • + Make correct code easier to write

Background Technologies

  • std::variant (C++17) or boost::variant
    • Gives equal importance to all members
  • std::optional (C++17), boost::optional
    • No extra information in the "null" state
  • More exotic: the Maybe/Either monads
  • Painfully close to what;s needed!

C++11: promise<T>/future<T>

  • Either a value of type T, or an exception
  • Primitives focused on inter-thread, async communication
  • We want eager, synchronous

Union Types

  • Discriminated unions
  • Defined by e.g. boost::any, variant
  • Typical implementation:

template <class T, class U> class Either {
    union { // Changed in C++11
        T t_;
        U u_;
    } data_;
    bool isT;
...
};

Unify local and centralized error handling:

  • expected<int, err> atoi(const char *);
    • Wanna local? Check result.has_value(), result.error()
    • Idiom: if (result) use(*result);
  • Wanna centralized? Just use *result
    • That is an int, or throws err if not

expected<T, E> characteristics

  • Associates errors with computational goals
  • Naturally allows multiple exceptions in flight
  • Switch between “error handling” and“exception throwing” styles
  • Teleportation possible
  • Across thread boundaries
  • Across nothrow subsystem boundaries
  • Across time: save now, throw later
  • Collect, group, combine exceptions

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.