Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/macros/template.md | +++
title = "Constrained template macros"
+++
*Overridable*: All of the following macros are overridable, define before inclusion.
*Header*: `<outcome/config.hpp>`
These macros expand into either the syntax for directly specifying constrained templates in C++ 20, or into a SFINAE based emulation for earlier C++ versions. Form of usage looks as follows:
```c++
OUTCOME_TEMPLATE(class ErrorCondEnum)
OUTCOME_TREQUIRES(
// If this is a valid expression
OUTCOME_TEXPR(error_type(make_error_code(ErrorCondEnum()))),
// If this predicate is true
OUTCOME_TPRED(predicate::template enable_error_condition_converting_constructor<ErrorCondEnum>)
// Any additional requirements follow here ...
)
constexpr basic_result(ErrorCondEnum &&t, error_condition_converting_constructor_tag /*unused*/ = {});
```
Be aware that slightly different semantics occur for real C++ 20 constrained templates than for the SFINAE emulation.
- <a name="template"></a>`OUTCOME_TEMPLATE(template args ...)`
Begins a constrained template declaration.
- <a name="trequires"></a>`OUTCOME_TREQUIRES(requirements ...)`
Specifies the requirements for the constrained template to be available for selection by the compiler.
- <a name="texpr"></a>`OUTCOME_TEXPR(expression)`
A requirement that the given expression is valid.
- <a name="tpred"></a>`OUTCOME_TPRED(boolean)`
A requirement that the given constant time expression is true.
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/macros/tryx.md | +++
title = "`OUTCOME_TRYX(expr)`"
description = "Evaluate an expression which results in an understood type, emitting the `T` if successful, immediately returning `try_operation_return_as(X)` from the calling function if unsuccessful."
+++
Evaluate an expression which results in a type matching the following customisation points, emitting the `T` if successful, immediately returning {{% api "try_operation_return_as(X)" %}} from the calling function if unsuccessful:
- `OUTCOME_V2_NAMESPACE::`{{% api "try_operation_has_value(X)" %}}
- `OUTCOME_V2_NAMESPACE::`{{% api "try_operation_return_as(X)" %}}
- `OUTCOME_V2_NAMESPACE::`{{% api "try_operation_extract_value(X)" %}}
Default overloads for these customisation points are provided. See [the recipe for supporting foreign input to `OUTCOME_TRY`]({{% relref "/recipes/foreign-try" %}}).
Hints are given to the compiler that the expression will be successful. If you expect failure, you should use {{% api "OUTCOME_TRYX_FAILURE_LIKELY(expr)" %}} instead.
An internal temporary to hold the value of the expression is created, which generally invokes a copy/move. [If you wish to never copy/move, you can tell this macro to create the internal temporary as a reference instead.]({{% relref "/tutorial/essential/result/try_ref" %}})
*Availability*: GCC and clang only. Use `#ifdef OUTCOME_TRYX` to determine if available.
*Overridable*: Not overridable.
*Definition*: See {{% api "OUTCOME_TRYV(expr)" %}} for most of the mechanics.
This macro makes use of a proprietary extension in GCC and clang to emit the `T` from a successful expression. You can thus use `OUTCOME_TRYX(expr)` directly in expressions e.g. `auto x = y + OUTCOME_TRYX(foo(z));`.
Be aware there are compiler quirks in preserving the rvalue/lvalue/etc-ness of emitted `T`'s, specifically copy or move constructors may be called unexpectedly and/or copy elision not work as expected. If these prove to be problematic, use {{% api "OUTCOME_TRY(var, expr)" %}} instead.
*Header*: `<outcome/try.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/_index.md | +++
title = "Policies"
weight = 40
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/throw_bad_result_access.md | +++
title = "`throw_bad_result_access<EC>`"
description = "Policy class defining that `bad_result_access_with<EC>` should be thrown on incorrect wide value observation. Inherits publicly from `base`."
+++
Policy class defining that {{% api "bad_result_access_with<EC>" %}} should be thrown on incorrect wide value observation. The primary purpose of this policy is to enable standing in for {{% api "std::expected<T, E>" %}} which throws a `bad_expected_access<E>` on incorrect wide value observation. This is why it is only ever `EC` which is thrown with `bad_result_access_with<EC>` on value observation only, and only when there is an error available.
If used in `basic_outcome`, and the outcome is exceptioned and so no error is available, incorrect wide value observation performs instead:
```c++
OUTCOME_THROW_EXCEPTION(bad_result_access("no value"));
```
Incorrect wide error observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_result_access("no error"));
```
Incorrect wide exception observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_outcome_access("no exception"));
```
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/throw_bad_result_access.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/exception_ptr_rethrow_outcome.md | +++
title = "`exception_ptr_rethrow<T, EC, EP>`"
description = "Policy class defining that the ADL discovered free function `rethrow_exception()` should be called on incorrect wide value observation. Inherits publicly from `base`. Can only be used with `basic_outcome`."
+++
*Note*: This policy class specialisation can only be used with `basic_outcome`, not `basic_result`. Use {{% api "exception_ptr_rethrow<T, EC, void>" %}} with `basic_result`.
Policy class defining that the ADL discovered free function `rethrow_exception(impl.assume_exception())` if possible, followed by `rethrow_exception(impl.assume_error())` should be called on incorrect wide value observation. Generally this will ADL discover {{% api "std::rethrow_exception()" %}} or `boost::rethrow_exception()` depending on the `EC` type.
Incorrect wide error observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_outcome_access("no error"));
```
Incorrect wide exception observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_outcome_access("no exception"));
```
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/outcome_exception_ptr_rethrow.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/exception_ptr_rethrow_result.md | +++
title = "`exception_ptr_rethrow<T, EC, void>`"
description = "Policy class defining that the ADL discovered free function `rethrow_exception()` should be called on incorrect wide value observation. Inherits publicly from `base`. Can only be used with `basic_result`."
+++
*Note*: This policy class specialisation can only be used with `basic_result`, not `basic_outcome`. Use {{% api "exception_ptr_rethrow<T, EC, EP>" %}} with `basic_outcome`.
Policy class defining that the ADL discovered free function `rethrow_exception(impl.assume_error())` should be called on incorrect wide value observation. Generally this will ADL discover {{% api "std::rethrow_exception()" %}} or `boost::rethrow_exception()` depending on the `EC` type.
Incorrect wide error observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_result_access("no error"));
```
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/result_exception_ptr_rethrow.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/error_code_throw_as_system_error_outcome.md | +++
title = "`error_code_throw_as_system_error<T, EC, EP>`"
description = "Policy class defining that `EP` ought to be rethrown if possible, then the ADL discovered free function `outcome_throw_as_system_error_with_payload()` should be called on incorrect wide value observation. Inherits publicly from `base`. Can only be used with `basic_outcome`."
+++
*Note*: This policy class specialisation can only be used with `basic_outcome`, not `basic_result`. Use {{% api "error_code_throw_as_system_error<T, EC, void>" %}} with `basic_result`.
Policy class defining that on incorrect wide value observation, `EP` ought to be rethrown if possible, then the ADL discovered free function `outcome_throw_as_system_error_with_payload(impl.assume_error())` should be called. [Some precanned overloads of that function are listed here]({{< relref "/reference/functions/policy" >}}).
Incorrect wide error observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_outcome_access("no error"));
```
Incorrect wide exception observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_outcome_access("no exception"));
```
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/outcome_error_code_throw_as_system_error.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/error_code_throw_as_system_error_result.md | +++
title = "`error_code_throw_as_system_error<T, EC, void>`"
description = "Policy class defining that the ADL discovered free function `outcome_throw_as_system_error_with_payload()` should be called on incorrect wide value observation. Inherits publicly from `base`. Can only be used with `basic_result`."
+++
*Note*: This policy class specialisation can only be used with `basic_result`, not `basic_outcome`. Use {{% api "error_code_throw_as_system_error<T, EC, EP>" %}} with `basic_outcome`.
Policy class defining that the ADL discovered free function `outcome_throw_as_system_error_with_payload(impl.assume_error())` should be called on incorrect wide value observation. [Some precanned overloads of that function are listed here]({{< relref "/reference/functions/policy" >}}).
Incorrect wide error observation performs:
```c++
OUTCOME_THROW_EXCEPTION(bad_result_access("no error"));
```
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/result_error_code_throw_as_system_error.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/all_narrow.md | +++
title = "`all_narrow`"
description = "Policy class defining that hard undefined behaviour should occur on incorrect narrow and wide value, error or exception observation. Inherits publicly from `base`."
+++
Policy class defining that hard undefined behaviour should occur on incorrect narrow and wide value, error or exception observation.
Inherits publicly from {{% api "base" %}}, and simply defines its wide value, error and exception observer policies to call their corresponding narrow editions.
Included by `<basic_result.hpp>`, and so is always available when `basic_result` is available.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/all_narrow.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/fail_to_compile_observers.md | +++
title = "`fail_to_compile_observers`"
description = "Policy class defining that a static assertion should occur upon compilation of the wide value, error or exception observation. Inherits publicly from `base`."
+++
Upon attempting to compile the wide observer policy functions, the following static assertion occurs which fails the build:
> *Attempt to wide observe value, error or exception for a result/outcome given an EC or E type which is not void, and for whom trait::has_error_code_v<EC>, trait::has_exception_ptr_v<EC>, and trait::has_exception_ptr_v<E> are all false. Please specify a NoValuePolicy to tell result/outcome what to do, or else use a more specific convenience type alias such as unchecked<T, E> to indicate you want the wide observers to be narrow, or checked<T, E> to indicate you always want an exception throw etc.*
This failure to compile was introduced after the Boost peer review of v2.0 of Outcome due to feedback that users were too often surprised by the default selection of the {{% api "all_narrow" %}} policy if the types were unrecognised. It was felt this introduced too much danger in the default configuration, so to ensure that existing code based on Outcome broke very loudly after an upgrade, the above very verbose static assertion was implemented.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/fail_to_compile_observers.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/policies/terminate.md | +++
title = "`terminate`"
description = "Policy class defining that `std::terminate()` should be called on incorrect wide value, error or exception observation. Inherits publicly from `base`."
+++
Policy class defining that {{% api "std::terminate()" %}} should be called on incorrect wide value, error or exception observation.
Inherits publicly from {{% api "base" %}}, and its narrow value, error and exception observer policies are inherited from there.
Included by `<basic_result.hpp>`, and so is always available when `basic_result` is available.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/terminate.hpp>`
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/exception.md | +++
title = "`static auto &&_exception(Impl &&) noexcept`"
description = "Returns a reference to the exception in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 270
+++
Returns a reference to the exception in the implementation passed in. No checking is done to ensure there is an error. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/narrow_error_check.md | +++
title = "`static void narrow_error_check(Impl &&) noexcept`"
description = "Observer policy performing hard UB if no error is present. Constexpr, never throws."
categories = ["observer-policies"]
weight = 410
+++
Observer policy performing hard UB if no error is present, by calling {{% api "static void _ub(Impl &&)" %}}. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_move_construction2.md | +++
title = "`static void on_outcome_move_construction(T *, U &&, V &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting move constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_outcome` (NOT the standard move constructor) which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_result_in_place_construction.md | +++
title = "`static void on_result_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the in-place constructors of `basic_result`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the in-place constructors of `basic_result`. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/set_has_value.md | +++
title = "`static void _set_has_value(Impl &&, bool) noexcept`"
description = "Sets whether the implementation has a value. Constexpr, never throws."
categories = ["modifiers"]
weight = 300
+++
Sets whether the implementation has a value by setting or clearing the relevant bit in the flags. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/_index.md | +++
title = "`base`"
description = "Base class of most policy classes defining the narrow observer policies."
+++
Implements the base class of most policy classes defining the narrow observer policies.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/policy/base.hpp>`
### Protected member functions
#### Special
{{% children description="true" depth="2" categories="special" %}}
#### Observers
{{% children description="true" depth="2" categories="observers" %}}
#### Modifiers
{{% children description="true" depth="2" categories="modifiers" %}}
### Public member functions
{{% children description="true" depth="2" categories="observer-policies" %}}
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/has_value.md | +++
title = "`static bool _has_value(Impl &&) noexcept`"
description = "Returns true if a value is present in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 200
+++
Returns true if a value is present in the implementation passed in. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_in_place_construction.md | +++
title = "`static void on_outcome_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the in-place constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the in-place constructors of `basic_outcome`. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/set_has_error_is_errno.md | +++
title = "`static void _set_has_exception(Impl &&, bool) noexcept`"
description = "Sets whether the implementation's error code has a domain or category matching that of POSIX `errno`. Constexpr, never throws."
categories = ["modifiers"]
weight = 340
+++
Sets whether the implementation's error code has a domain or category matching that of POSIX `errno` by setting or clearing the relevant bit in the flags. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_result_construction.md | +++
title = "`static void on_result_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the implicit constructors of `basic_result`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_result`. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/narrow_value_check.md | +++
title = "`static void narrow_value_check(Impl &&) noexcept`"
description = "Observer policy performing hard UB if no value is present. Constexpr, never throws."
categories = ["observer-policies"]
weight = 400
+++
Observer policy performing hard UB if no value is present, by calling {{% api "static void _ub(Impl &&)" %}}. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/error.md | +++
title = "`static auto &&_error(Impl &&) noexcept`"
description = "Returns a reference to the error in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 260
+++
Returns a reference to the error in the implementation passed in. No checking is done to ensure there is an error. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/set_has_error.md | +++
title = "`static void _set_has_error(Impl &&, bool) noexcept`"
description = "Sets whether the implementation has an error. Constexpr, never throws."
categories = ["modifiers"]
weight = 310
+++
Sets whether the implementation has an error by setting or clearing the relevant bit in the flags. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_result_copy_construction.md | +++
title = "`static void on_result_copy_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting copy constructors of `basic_result`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_result` (NOT the standard copy constructor). See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_construction2.md | +++
title = "`static void on_outcome_construction(T *, U &&, V &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the implicit constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_outcome` which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/has_error_is_errno.md | +++
title = "`static bool _has_error_is_errno(Impl &&) noexcept`"
description = "Returns true if the error code in the implementation passed in has a domain or category matching that of POSIX `errno`. Constexpr, never throws."
categories = ["observers"]
weight = 240
+++
Returns true if the error code in the implementation passed in has a domain or category matching that of POSIX `errno`. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/set_has_exception.md | +++
title = "`static void _set_has_exception(Impl &&, bool) noexcept`"
description = "Sets whether the implementation has an exception. Constexpr, never throws."
categories = ["modifiers"]
weight = 330
+++
Sets whether the implementation has an exception by setting or clearing the relevant bit in the flags. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/has_error.md | +++
title = "`static bool _has_error(Impl &&) noexcept`"
description = "Returns true if an error is present in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 210
+++
Returns true if an error is present in the implementation passed in. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/narrow_exception_check.md | +++
title = "`static void narrow_exception_check(Impl &&) noexcept`"
description = "Observer policy performing hard UB if no exception is present. Constexpr, never throws."
categories = ["observer-policies"]
weight = 420
+++
Observer policy performing hard UB if no exception is present, by calling {{% api "static void _ub(Impl &&)" %}}. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_copy_construction.md | +++
title = "`static void on_outcome_copy_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting copy constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_outcome` (NOT the standard copy constructor). See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_construction.md | +++
title = "`static void on_outcome_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the implicit constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_outcome`. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_copy_construction2.md | +++
title = "`static void on_outcome_copy_construction(T *, U &&, V &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting copy constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_outcome` (NOT the standard copy constructor) which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_result_move_construction.md | +++
title = "`static void on_result_move_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting move constructors of `basic_result`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_result` (NOT the standard move constructor). See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/on_outcome_move_construction.md | +++
title = "`static void on_outcome_move_construction(T *, U &&) noexcept`"
description = "(>= Outcome v2.2.0) Hook invoked by the converting move constructors of `basic_outcome`."
categories = ["observer-policies"]
weight = 450
+++
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_outcome` (NOT the standard move constructor). See each constructor's documentation to see which specific hook it invokes.
*Requires*: Always available.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/has_exception.md | +++
title = "`static bool _has_exception(Impl &&) noexcept`"
description = "Returns true if an exception is present in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 230
+++
Returns true if an exception is present in the implementation passed in. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/ub.md | +++
title = "`static void _ub(Impl &&)`"
description = "Special function which causes noticeable hard undefined behaviour."
categories = ["special"]
weight = 100
+++
This is a special function which does compiler-specific stuff to tell the compiler that this function can never, ever, ever be executed. The compiler's optimiser will **hard assume** that this function can never be executed, and will prune the possibility of it being executed completely. Generally this means that the code path stops dead, and if execution does proceed down this path, it will run off the end of a branch which doesn't go anywhere. Your program will have lost known state, and usually it will trash memory and registers and crash.
This may seem highly undesirable. However, it also means that the optimiser can optimise more strongly, and so long as you never actually do execute this branch, you do get higher quality code generation.
If the `NDEBUG` macro is not defined, an `OUTCOME_ASSERT(false)` is present. This will cause attempts to execute this function to fail in a very obvious way, but it also generates runtime code to trigger the obvious failure.
If the `NDEBUG` macro is defined, and the program is compiled with the undefined behaviour sanitiser, attempts to execute this function will trigger an undefined behaviour sanitiser action.
*Requires*: Always available.
*Complexity*: Zero runtime overhead if `NDEBUG` is defined, guaranteed. If this function returns, your program is now in hard loss of known program state. *Usually*, but not always, it will crash at some point later. *Rarely* it will corrupt registers and memory, and keep going.
*Guarantees*: An exception is never thrown.
|
0 | repos/outcome/doc/src/content/reference/policies | repos/outcome/doc/src/content/reference/policies/base/value.md | +++
title = "`static auto &&_value(Impl &&) noexcept`"
description = "Returns a reference to the value in the implementation passed in. Constexpr, never throws."
categories = ["observers"]
weight = 250
+++
Returns a reference to the value in the implementation passed in. No checking is done to ensure there is a value. Constexpr where possible.
*Requires*: Always available.
*Complexity*: Constant time.
*Guarantees*: Never throws an exception.
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/try_operation_return_as.md | +++
title = "`decltype(auto) try_operation_return_as(X)`"
description = "Default implementation of `try_operation_return_as(X)` ADL customisation point for `OUTCOME_TRY`."
+++
This default implementation preferentially returns whatever the input type's `.as_failure()` member function returns.
`basic_result` and `basic_outcome` provide such a member function, see {{% api "auto as_failure() const &" %}}.
If `.as_failure()` is not available, it will also match any `.error()` member function, which it wraps into a failure type sugar using {{% api "failure(T &&, ...)" %}}.
*Requires*: That the expression `std::declval<T>().as_failure()` and/or `std::declval<T>().error()` is a valid expression.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/try.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/success.md | +++
title = "`auto success(T &&, ...)`"
description = "Returns appropriate type sugar for constructing a successful result or outcome."
+++
Returns appropriate type sugar for constructing a successful result or outcome, usually {{% api "success_type<T>" %}} with a decayed `T`.
Two default overloads are provided, one taking a single required parameter with optional spare storage value parameter returning `success_type<std::decay_t<T>>` and perfectly forwarding the input. The other overload takes no parameters, and returns `success_type<void>`, which usually causes the construction of the receiving `basic_result` or `basic_outcome`'s with a default construction of their value type.
*Overridable*: By Argument Dependent Lookup (ADL).
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/success_failure.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/_index.md | +++
title = "Functions"
weight = 70
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/try_throw_std_exception_from_error.md | +++
title = "`void try_throw_std_exception_from_error(std::error_code ec, const std::string &msg = std::string{})`"
description = "Try to throw a standard library exception type matching an error code."
+++
This function saves writing boilerplate by throwing a standard library exception
type equivalent to the supplied error code, with an optional custom message.
If the function returns, there is no standard library exception type equivalent
to the supplied error code. The following codes produce the following exception
throws:
<dl>
<dt><code>EINVAL</code>
<dd><code>std::invalid_argument</code>
<dt><code>EDOM</code>
<dd><code>std::domain_error</code>
<dt><code>E2BIG</code>
<dd><code>std::length_error</code>
<dt><code>ERANGE</code>
<dd><code>std::out_of_range</code>
<dt><code>EOVERFLOW</code>
<dd><code>std::overflow_error</code>
<dt><code>ENOMEM</code>
<dd><code>std::bad_alloc</code>
</dl>
The choice to refer to POSIX `errno` values above reflects the matching algorithm.
As {{% api "std::errc" %}} exactly maps POSIX `errno`, on all platforms
{{% api "std::generic_category" %}} error codes are matched by this function.
Only on POSIX platforms only are {{% api "std::system_category" %}} error codes
also matched by this function.
*Overridable*: Not overridable.
*Requires*: C++ exceptions to be globally enabled.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/utils.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/strong_swap.md | +++
title = "`void strong_swap(bool &all_good, T &a, T &b)`"
description = "Tries to perform a strong guarantee swap."
+++
The standard `swap()` function provides the weak guarantee i.e. that no resources are lost. This ADL discovered function provides the strong guarantee instead: that if any of these operations throw an exception (i) move construct to temporary (ii) move assign `b` to `a` (iii) move assign temporary to `b`, an attempt is made to restore the exact pre-swapped state upon entry, and if that recovery too fails, then the boolean `all_good` will be false during stack unwind from the exception throw, to indicate that state has been lost.
This function is used within `basic_result::`{{% api "swap(basic_result &)" %}} if, and only if, either or both of `value_type` or `error_type` have a throwing move constructor or move assignment. It permits you to customise the implementation of the strong guarantee swap in Outcome with a more efficient implementation.
*Overridable*: By Argument Dependent Lookup (ADL).
*Requires*: That `T` is both move constructible and move assignable.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/error_from_exception.md | +++
title = "`std::error_code error_from_exception(std::exception_ptr &&ep = std::current_exception(), std::error_code not_matched = std::make_error_code(std::errc::resource_unavailable_try_again)) noexcept`"
description = "Returns an error code matching a thrown standard library exception."
+++
This function saves writing boilerplate by rethrowing `ep` within a `try`
block, with a long sequence of `catch()` handlers, one for every standard
C++ exception type which has a near or exact equivalent code in {{% api "std::errc" %}}.
If matched, `ep` is set to a default constructed {{% api "std::exception_ptr" %}},
and a {{% api "std::error_code" %}} is constructed using the ADL discovered free
function `make_error_code()` upon the `std::errc` enumeration value matching the
thrown exception.
If not matched, `ep` is left intact, and the `not_matched` error code supplied
is returned instead.
*Overridable*: Not overridable.
*Requires*: C++ exceptions to be globally enabled.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/utils.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/failure.md | +++
title = "`auto failure(T &&, ...)`"
description = "Returns appropriate type sugar for constructing an unsuccessful result or outcome."
+++
Returns appropriate type sugar for constructing an unsuccessful result or outcome, usually {{% api "failure_type<EC, EP = void>" %}} with a decayed `T`.
Two default overloads are provided, one taking a single required parameter with optional spare storage value parameter returning `failure_type<std::decay_t<T>>`, the other taking two required parameters with optional spare storage value parameter returning `failure_type<std::decay_t<T>, std::decay_t<U>>`. Both overloads perfectly forward their inputs.
Note that `failure()` overloads are permitted by Outcome to return something other than `failure_type`. For example, `basic_result`'s {{% api "auto as_failure() const &" %}} returns whatever type `failure()` returns, and {{% api "OUTCOME_TRY(var, expr)" %}} by default returns for failure whatever `.as_failure()` returns. This can be useful to have `OUTCOME_TRY(...}` propagate on failure something custom for some specific input `basic_result` or `basic_outcome`.
*Overridable*: By Argument Dependent Lookup (ADL).
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/success_failure.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/try_operation_extract_value.md | +++
title = "`decltype(auto) try_operation_extract_value(X)`"
description = "Default implementation of `try_operation_extract_value(X)` ADL customisation point for `OUTCOME_TRY`."
+++
This default implementation returns whatever the `.assume_value()` or `.value()` member functions return, preferentially choosing the former where both are available.
*Requires*: That the expression `std::declval<T>().assume_value()` and/or `std::declval<T>().value()` is a valid expression.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/try.hpp>`
|
0 | repos/outcome/doc/src/content/reference | repos/outcome/doc/src/content/reference/functions/try_operation_has_value.md | +++
title = "`bool try_operation_has_value(X)`"
description = "Default implementation of `try_operation_has_value(X)` ADL customisation point for `OUTCOME_TRY`."
+++
This default implementation returns whatever the `.has_value()` member function returns.
*Requires*: That the expression `std::declval<T>().has_value()` is a valid expression.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/try.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/outcome_throw_as_system_error_with_payload_boost_enum.md | +++
title = "`void outcome_throw_as_system_error_with_payload(BoostErrorCodeEnum &&)`"
description = "Specialisation of `outcome_throw_as_system_error_with_payload()` for input types where `boost::system::is_error_code_enum<BoostErrorCodeEnum>` or `boost::system::is_error_condition_enum<BoostErrorCodeEnum>` is true."
+++
A specialisation of `outcome_throw_as_system_error_with_payload()` for types where `boost::system::is_error_code_enum<BoostErrorCodeEnum>` or `boost::system::is_error_condition_enum<BoostErrorCodeEnum>` is true. This executes {{% api "OUTCOME_THROW_EXCEPTION(expr)" %}} with a `boost::system::system_error` constructed from the result of the ADL discovered free function `make_error_code(BoostErrorCodeEnum)`.
*Overridable*: Argument dependent lookup.
*Requires*: Either `boost::system::is_error_code_enum<T>` or `boost::system::is_error_condition_enum<T>` to be true for a decayed `BoostErrorCodeEnum`.
*Namespace*: `boost::system`
*Header*: `<outcome/boost_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/outcome_throw_as_system_error_with_payload_std_error_code.md | +++
title = "`void outcome_throw_as_system_error_with_payload(const std::error_code &)`"
description = "Specialisation of `outcome_throw_as_system_error_with_payload()` for `std::error_code`."
+++
A specialisation of `outcome_throw_as_system_error_with_payload()` for `std::error_code`. This executes {{% api "OUTCOME_THROW_EXCEPTION(expr)" %}} with a {{% api "std::system_error" %}} constructed from the input.
*Overridable*: Argument dependent lookup.
*Requires*: Nothing.
*Namespace*: `std`
*Header*: `<outcome/std_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/_index.md | +++
title = "Policy"
description = "Functions used to customise how the policy classes operate."
weight = 40
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/exception_ptr.md | +++
title = "`decltype(auto) exception_ptr(T &&)`"
description = "Extracts a `boost::exception_ptr` or `std::exception_ptr` from the input via ADL discovery of a suitable `make_exception_ptr(T)` function."
+++
Extracts a `boost::exception_ptr` or {{% api "std::exception_ptr" %}} from the input via ADL discovery of a suitable `make_exception_ptr(T)` function.
*Overridable*: Argument dependent lookup.
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/std_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/error_code.md | +++
title = "`decltype(auto) error_code(T &&)`"
description = "Extracts a `boost::system::error_code` or `std::error_code` from the input via ADL discovery of a suitable `make_error_code(T)` function."
+++
Extracts a `boost::system::error_code` or {{% api "std::error_code" %}} from the input via ADL discovery of a suitable `make_error_code(T)` function.
*Overridable*: Argument dependent lookup.
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE::policy`
*Header*: `<outcome/std_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/basic_outcome_failure_exception_from_error.md | +++
title = "`auto basic_outcome_failure_exception_from_error(const EC &)`"
description = "ADL discovered free function synthesising an exception type from an error type, used by the `.failure()` observers."
+++
Synthesises an exception type from an error type, used by the {{% api "exception_type failure() const noexcept" %}}
observers. ADL discovered. Default
overloads for this function are defined in Outcome for {{% api "std::error_code" %}}
and `boost::system::error_code`, these return `std::make_exception_ptr(std::system_error(ec))`
and `boost::copy_exception(boost::system::system_error(ec))` respectively.
*Overridable*: Argument dependent lookup.
*Requires*: Nothing.
*Namespace*: Namespace of `EC` type.
*Header*: `<outcome/std_outcome.hpp>`, `<outcome/boost_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/outcome_throw_as_system_error_with_payload_boost_error_code.md | +++
title = "`void outcome_throw_as_system_error_with_payload(const boost::system::error_code &)`"
description = "Specialisation of `outcome_throw_as_system_error_with_payload()` for `boost::system::error_code`."
+++
A specialisation of `outcome_throw_as_system_error_with_payload()` for `boost::system::error_code`. This executes {{% api "OUTCOME_THROW_EXCEPTION(expr)" %}} with a `boost::system::system_error` constructed from the input.
*Overridable*: Argument dependent lookup.
*Requires*: Nothing.
*Namespace*: `boost::system`
*Header*: `<outcome/boost_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/policy/outcome_throw_as_system_error_with_payload_std_enum.md | +++
title = "`void outcome_throw_as_system_error_with_payload(ErrorCodeEnum &&)`"
description = "Specialisation of `outcome_throw_as_system_error_with_payload()` for input types where `std::is_error_code_enum<ErrorCodeEnum>` or `std::is_error_condition_enum<ErrorCodeEnum>` is true."
+++
A specialisation of `outcome_throw_as_system_error_with_payload()` for types where `std::is_error_code_enum<ErrorCodeEnum>` or `std::is_error_condition_enum<ErrorCodeEnum>` is true. This executes {{% api "OUTCOME_THROW_EXCEPTION(expr)" %}} with a {{% api "std::system_error" %}} constructed from the result of the ADL discovered free function `make_error_code(ErrorCodeEnum)`.
*Overridable*: Argument dependent lookup.
*Requires*: Either {{% api "std::is_error_code_enum<T>" %}} or {{% api "std::is_error_condition_enum<T>" %}} to be true for a decayed `ErrorCodeEnum`.
*Namespace*: `std`
*Header*: `<outcome/std_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/spare_storage.md | +++
title = "`uint16_t spare_storage(const basic_result|basic_outcome *) noexcept`"
description = "Returns the sixteen bits of spare storage in the specified result or outcome."
+++
Returns the sixteen bits of spare storage in the specified result or outcome. You can set these bits using {{% api "void set_spare_storage(basic_result|basic_outcome *, uint16_t) noexcept" %}}.
*Overridable*: Not overridable.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/_index.md | +++
title = "Hooks"
description = "Functions used to hook into the functionality of `basic_result` and `basic_outcome`."
weight = 30
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_copy_construction2.md | +++
title = "`void hook_outcome_copy_construction(T *, U &&, V &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting copy constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_copy_construction(T *, U &&, V &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_outcome` (NOT the standard copy constructor) which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/override_outcome_exception.md | +++
title = "`void override_outcome_exception(basic_outcome<T, EC, EP, NoValuePolicy> *, U &&) noexcept`"
description = "Overrides the exception to something other than what was constructed."
+++
Overrides the exception to something other than what was constructed. You *almost certainly* never
want to use this function. A much better way of overriding the exception returned is to create
a custom no-value policy which lazily synthesises a custom exception object at the point of need.
The only reason that this function exists is because some people have very corner case needs
where a custom no-value policy can't be used, and where move-constructing a new `outcome` from
an old `outcome` with the exception state replaced isn't possible (e.g. when the types are
non-copyable and non-moveable).
Unless you are in a situation where no other viable alternative exists, do not use this function.
*Overridable*: Not overridable.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_construction2.md | +++
title = "`void hook_outcome_construction(T *, U &&, V &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the implicit constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_construction(T *, U &&, V &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_outcome` which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_result_move_construction.md | +++
title = "`void hook_result_move_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting move constructors of `basic_result`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_result_move_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_result` (NOT the standard move constructor). See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_result_copy_construction.md | +++
title = "`void hook_result_copy_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting copy constructors of `basic_result`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_result_copy_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_result` (NOT the standard copy constructor). See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_result_construction.md | +++
title = "`void hook_result_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the implicit constructors of `basic_result`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_result_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_result`. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_copy_construction.md | +++
title = "`void hook_outcome_copy_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting copy constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_copy_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting copy constructors of `basic_outcome` (NOT the standard copy constructor). See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_construction.md | +++
title = "`void hook_outcome_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the implicit constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the implicit constructors of `basic_outcome`. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_move_construction.md | +++
title = "`void hook_outcome_move_construction(T *, U &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting move constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_move_construction(T *, U &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_outcome` (NOT the standard move constructor). See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_result_in_place_construction.md | +++
title = "`void hook_result_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the in-place constructors of `basic_result`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_result_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_result<T, E, NoValuePolicy>" %}}, generally invoked by the in-place constructors of `basic_result`. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_in_place_construction.md | +++
title = "`void hook_outcome_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the in-place constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_in_place_construction(T *, in_place_type_t<U>, Args &&...) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the in-place constructors of `basic_outcome`. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/hook_outcome_move_construction2.md | +++
title = "`void hook_outcome_move_construction(T *, U &&, V &&) noexcept`"
description = "(Until v2.2.0) ADL discovered free function hook invoked by the converting move constructors of `basic_outcome`."
+++
Removed in Outcome v2.2.0, unless {{% api "OUTCOME_ENABLE_LEGACY_SUPPORT_FOR" %}} is set to less than `220` to
enable emulation. Use {{% api "on_outcome_move_construction(T *, U &&, V &&) noexcept" %}} instead in new code.
One of the constructor hooks for {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}, generally invoked by the converting move constructors of `basic_outcome` (NOT the standard move constructor) which consume two arguments. See each constructor's documentation to see which specific hook it invokes.
*Overridable*: By Argument Dependent Lookup.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_outcome.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/hooks/set_spare_storage.md | +++
title = "`void set_spare_storage(basic_result|basic_outcome *, uint16_t) noexcept`"
description = "Sets the sixteen bits of spare storage in the specified result or outcome."
+++
Sets the sixteen bits of spare storage in the specified result or outcome. You can retrieve these bits later using {{% api "uint16_t spare_storage(const basic_result|basic_outcome *) noexcept" %}}.
*Overridable*: Not overridable.
*Requires*: Nothing.
*Namespace*: `OUTCOME_V2_NAMESPACE::hooks`
*Header*: `<outcome/basic_result.hpp>`
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/_index.md | +++
title = "Iostream"
description = "Functions used to print, serialise and deserialise `basic_result` and `basic_outcome`."
weight = 35
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/outcome_operator_out.md | +++
title = "`std::ostream &operator<<(std::ostream &, const basic_outcome<T, EC, EP, NoValuePolicy> &)`"
description = "Serialises a `basic_outcome` to a `std::ostream`."
+++
Serialises a `basic_outcome` to a `std::ostream`.
Serialisation format is:
```
<unsigned int flags><space><value_type if set and not void><error_type if set and not void><exception_type if set and not void>
```
This is the **wrong** function to use if you wish to print human readable output.
Use {{% api "std::string print(const basic_outcome<T, EC, EP, NoValuePolicy> &)" %}} instead.
*Overridable*: Not overridable.
*Requires*: That `operator<<` is a valid expression for `std::ostream` and `T`, `EC` and `EP`.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/outcome_operator_in.md | +++
title = "`std::istream &operator>>(std::istream &, basic_outcome<T, EC, EP, NoValuePolicy> &)`"
description = "Deserialises a `basic_outcome` from a `std::istream`."
+++
Deserialises a `basic_outcome` from a `std::istream`.
Serialisation format is:
```
<unsigned int flags><space><value_type if set and not void><error_type if set and not void><exception_type if set and not void>
```
*Overridable*: Not overridable.
*Requires*: That `operator>>` is a valid expression for `std::istream` and `T`, `EC` and `EP`.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/result_operator_in.md | +++
title = "`std::istream &operator>>(std::istream &, basic_result<T, E, NoValuePolicy> &)`"
description = "Deserialises a `basic_result` from a `std::istream`."
+++
Deserialises a `basic_result` from a `std::istream`.
Serialisation format is:
```
<unsigned int flags><space><value_type if set and not void><error_type if set and not void>
```
*Overridable*: Not overridable.
*Requires*: That `operator>>` is a valid expression for `std::istream` and `T` and `E`.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/result_operator_out.md | +++
title = "`std::ostream &operator<<(std::ostream &, const basic_result<T, E, NoValuePolicy> &)`"
description = "Serialises a `basic_result` to a `std::ostream`."
+++
Serialises a `basic_result` to a `std::ostream`.
Serialisation format is:
```
<unsigned int flags><space><value_type if set and not void><error_type if set and not void>
```
This is the **wrong** function to use if you wish to print human readable output.
Use {{% api "std::string print(const basic_result<T, E, NoValuePolicy> &)" %}} instead.
*Overridable*: Not overridable.
*Requires*: That `operator<<` is a valid expression for `std::ostream` and `T` and `E`.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/outcome_print.md | +++
title = "`std::string print(const basic_outcome<T, EC, EP, NoValuePolicy> &)`"
description = "Returns a string containing a human readable rendition of the `basic_outcome`."
+++
Returns a string containing a human readable rendition of the `basic_outcome`.
*Overridable*: Not overridable.
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content/reference/functions | repos/outcome/doc/src/content/reference/functions/iostream/result_print.md | +++
title = "`std::string print(const basic_result<T, E, NoValuePolicy> &)`"
description = "Returns a string containing a human readable rendition of the `basic_result`."
+++
Returns a string containing a human readable rendition of the `basic_result`.
*Overridable*: Not overridable.
*Requires*: Always available.
*Namespace*: `OUTCOME_V2_NAMESPACE`
*Header*: `<outcome/iostream_support.hpp>` (must be explicitly included manually).
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/requirements/_index.md | +++
title = "Prerequisites"
weight = 2
+++
Outcome is a header-only C++ 14 library known to work well on the latest
point releases of these compiler-platform combinations or better:
- clang 4.0.1 (LLVM) [FreeBSD, Linux, OS X]
- GCC 6.5 [Linux]
- Visual Studio 2017.9 [Windows]
- XCode 9 [MacOS]
For non-Windows non-POSIX platforms (typically embedded systems), Outcome
is usable in its Outcome.Experimental form with the macro `SYSTEM_ERROR2_NOT_POSIX`
defined.
It is worth turning on C++ 17 or C++ 20 if you can, as there are many usability and
performance improvements. Any Concepts TS or Coroutines TS implemented
by your compiler is automatically detected and used.
Known compiler issues (this was last updated April 2023):
- clang 3.5 - 3.9 can compile varying degrees of the test suite, the
problem is lack of complete and unbuggy C++ 14 language support.
- Older point releases of GCCs 7 and 8 have internal compiler error bugs
in their constexpr implementation which tend to be triggered by using
Outcome in constexpr. If you don't use Outcome in constexpr, you won't
see these problems. If you need your GCC to not ICE, upgrade to the
very latest point release, the constexpr ICE has been since fixed.
- Early editions of Visual Studio 2017 have many corner case problems.
From VS2017.9 onwards there remain a number of usually untroublesome corner
case issues, but use should be relatively unsurprising for most use cases.
Be aware that only from Visual Studio 2022 onwards are almost all corner
case problems fixed.
- Some point releases of GCC 10 with libstdc++ 10 can induce an infinite
template instantiation, which fails the build for some rare use cases. Earlier
or later GCCs or different point releases of the 10 series do not have
this issue.
---
"C++ 14" compilers which do not work, and will not work until their
maintainers fix them:
- GCC 5, due to a bug in nested template variables parsing which was fixed
in GCC 6. I appreciate that this upsets a lot of users. Please raise your
upset at https://gcc.gnu.org/bugzilla/. In the meantime, you can get fairly
far in Outcome with even clang 3.5.
- Any compiler which uses the libstdc++ version which comes with GCC 5, as it does
not implement enough of the C++ 14 standard library for Outcome to compile.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/history/_index.md | +++
title = "History"
weight = 90
+++
Outcome has had an interesting history, and it is worth summarising it here to show how a
Boost library comes to life. The following recollections are by Niall Douglas, and may be
faulty due to his aging memory.
{{<if_boost "/history/graph.png">}}
{{<mermaid>}}
gantt
dateFormat YYYY-MM
title History of the Outcome library
Outcome v1: done, des1, 2014-06,2017-05
Boost peer review of v1: done, des2, after des1, 30d
Outcome v2 (complete redesign based on first review feedback): done, des3, after des2, 2018-01
Boost peer review of v2: done, des4, after des3, 30d
Outcome v2.1 (changes from second review): active, des5, 2018-03, 2021-04
Outcome v2.2 (changes from user feedback on v2.1): des6, after des5, 2023-04
section Events
Separated from AFIO v1: crit, done, 2014-06,4d
Boost.Expected added: crit, done, 2014-10,4d
Boost.Expected replaced with feature complete basic_monad: crit, done, 2015-08,4d
Non-allocating future-promise implementation dropped: crit, done, 2016-05,4d
C++ 11 support dropped: crit, done, 2016-06,4d
Implemented LEWG expected<T, E> using basic_monad: crit, done, 2017-02,4d
Outcome v1 replaced with prototype v2 in git repo: crit, done, 2017-07,4d
Boost.Outcome generated by script from Outcome repo: crit, done, 2017-10,4d
New tutorial finally complete: crit, done, 2017-12,4d
Outcome v2.1 feature complete, maturation begins: crit, done, 2018-04,4d
Boost.Outcome docs gain BoostDoc theming: crit, done, 2018-12,4d
Release of v2.1 into Boost 1.70: crit, active, 2019-04,4d
Release of v2.2 into Boost 1.76: crit, active, 2021-04,4d
Outcome goes ABI stable: crit, active, 2022-04,4d
{{</mermaid>}}
{{</if_boost>}}
## The genesis of Outcome v1 (2014 - 2017)
The git repo began life as a "Boost.Spinlock" in June 2014 hived out of Boost.AFIO v1 where it had existed
for some time as an internal library. In October 2014 I added in the original prototype
Boost.Expected reference library as a git submodule, and began developing a non-allocating
`future<T>`/`promise<T>` as an extension of `expected<T, std::exception_ptr>` as a faster,
monadic future-promise was something which AFIO v1 sorely needed.
The original prototype Boost.Expected library was a large and very complex beastie.
I was fortunate to be employed on a contract in late 2014 early 2015 where I saw it deployed at
scale into an existing large C++ codebase. Expected was really great and powerful, but it absolutely
murdered compile times in a large C++ codebase, and made LTO effectively infeasible.
I also found its implementation non-conducive to implementing
future-promise with it, and so I resolved to implement a much more powerful policy driven
monad factory which could stamp out everything from an `option<T>` right through to a
future-promise pair, all using the exact same `basic_monad<>` and therefore all with a full
monadic programming API, C++ 17 continuations/monadic bind and intelligently convertible into one another.
Moreover, all this needed to have an absolute minimum impact on compile times and runtime
overheads, neither of which were strengths of the original prototype Boost.Expected library.
By August 2015 "Boost.Monad" was delivering on all those requirements and then some, but it lacked
maturity through use in other code. Summer 2015 saw the Boost peer review of AFIO v1 which
was roundly rejected. After considering the ample review feedback, it was realised that
[AFIO v2](https://ned14.github.io/llfio/) would be a very different design, one no longer using futures, memory allocation
nor C++ exceptions. As AFIO v2 was started from scratch and using Outcome heavily from the
very beginning (every AFIO v2 API returns a `result<T>`), Outcome began to gain bug fixes and
shed features, with the non-allocating future-promise implementation being dropped in May
2016 and a large chunk of type based metaprogramming being replaced with cleaner variable template metaprogramming
in June. After CppCon 2016 in September, then began the long process of getting Outcome
ready for Boost peer review in Q1 2017 which involved a repeated sequence of complete rewrites
of the tutorial in response to multiple rounds of feedback from the C++ community, with
at least four complete rewrites currently at the time of writing.
In parallel to all this development on Outcome, Expected went before the LEWG and entered
the C++ standards track. As the WG21 meetings went by, Expected experienced a period
of being stripped back and much of the complexity which had so murdered compile and
link times in 2014-2015 fell away, thus the Expected proposed in P0323R1 ended up landing
so close to Outcome that in January 2017 it was just a few hours work to implement
Expected using the core `basic_monad` infrastructure in Outcome. That highly flexible
policy based design which made monadic future-promise possible made it similarly easy
to implement a highly conforming Expected, indeed in early 2017 Outcome's Expected was much
closer to [P0323R1](http://wg21.link/P0323) than any other implementation including the LEWG reference implementation.
And unlike the LEWG reference implementation, Outcome has had eighteen months of that
finely tuned patina you only get when a library is in use by other code bases.
In February 2017 it became realised that the userbase really wanted a high quality `expected<T, E>`
implementation rather than anything similar but not the same which Outcome had invented.
The only just implemented Expected implementation based on `basic_monad` therefore took
primacy. The final rewrite of the documentation before peer review submission was one
which made it look like Outcome was primarily an `expected<T, E>` implementation with a
few useful extensions like `outcome<T>` and `result<T>`. I was sad to so pivot, but it
was obvious that Outcome would see far wider popularity and usage as primarily an Expected
implementation.
Almost three years after its beginning, Outcome v1 finally went before Boost peer review
in May 2017 which turned into one of the longest and most detailed peer reviews Boost has
done in recent years, with over 800 pieces of review feedback submitted. It was by consensus
rejected, [with substantial feedback on what to do instead](https://lists.boost.org/boost-announce/2017/06/0510.php).
## Outcome v2 (2018)
During the very lengthy peer review, roughly three groups of opinion emerged as to what
a `value|error` transporting class ought to look like:
<dl>
<dt><b>1. Lightweight</b></dt>
<dd>A simple-as-possible <code>T</code> and/or <code>E</code> transport without any
implementation complexity.</dd>
<dt><b>2. Medium</b></dt>
<dd>A variant stored <code>T</code> or <code>E1</code> ... <code>E<i>n</i></code>
where <code>T</code> is the expected value and <code>E1 ...</code>
are the potential unexpected values. This implemention really ought to be implemented
using C++ 17's <code>std::variant<...></code> except with stronger never-empty guarantees.
</dd>
<dt><b>3. Heavy</b></dt>
<dd>A full fat Either monad participating fully in a wider monadic programming framework for C++.</dd>
</dl>
Peter Dimov was very quickly able to implement an `expected<T, E1, ...>` using his
[variant2](https://github.com/pdimov/variant2) library, and thus there seemed little
point in replicating his work in an Outcome v2. The lightweight choice seemed to be the
best path forwards, so in June 2017 the bare minimum `result<T, E>` and `outcome<T, EC, P>`
as presented in this library was built, using the same constructor design as `std::variant<...>`.
Significant backwards compatibility with v1 Outcome code was retained, as the review
had felt the basic proposed design fine.
A period of maturation then followed by porting a large existing codebase using Outcome v1
to v2, and writing a significant amount of new code using v2 to test it for unanticipated
surprises and bugs. Quite a few corner cases were found and fixed. At the end of September
2017, Outcome v2 was deemed to be "mature", and a script generated "Boost edition" made
available.
All that remained before it was ready for a second Boost peer review was the
documentation. This took four months to write (same time as to write the library itself!),
and in January 2018 Outcome had its second Boost peer review, which it passed!
## Outcome v2.1 (2019 - 2020)
The changes requsted during the review of v2.0 were fairly modest: `result` and `outcome` would
be renamed to `basic_result` and `basic_outcome`, and a clean separation of concerns between the
`basic_*` layer and the "convenience" layer would be created. That suited Outcome nicely,
as the `basic_*` layer could have minimum possible header dependencies and thus minimum possible build times
impact, which was great for big iron users with multi-million line C++ codebases. This also
had the nice side effect of permitting both Boost and `std` implementations to be supported
concurrently in both Outcome and Boost.Outcome.
By April 2018, v2.1 was feature complete and entered a six month period of maturation and
battle hardening under its already extensive userbase. However Outcome passing its review in January 2018 had much more consequence than I could have ever
expected. Unbeknownst to me, some of the WG21 leadership had interpreted the success of
Outcome, and especially its divergences from WG21 Expected into a more complete substitute
for C++ exception handling, as a sign that the C++
exception handling mechanism was no longer fit for purpose. [It was thus proposed
to remedy the standard exception handling mechanism into something much more
efficient, thus rendering Outcome obsolete in future C++ standards (P0709 *Zero overhead exceptions*)](http://wg21.link/P0709).
Concurrently to that, just before the review of Outcome 2.0, I had mooted a number of semantic and compile time performance
improvements to `<system_error>` with the proposal that we mildly break Boost.System with
improvements and see how badly real world code broke in response. This was not widely
accepted at that time (though they have been since incorporated into Boost.System, and proposed
defect remedies for `<system_error>` for C++ 23). I therefore wrote [an improved `<system_error2>`](https://ned14.github.io/status-code/) which fixed all the problems
listed at [P0824 (Summary of SG14 discussion on `<system_error>`)](https://wg21.link/P0824)
and fixed up Outcome so one could use it without any system error implementation,
or with the STL one or with the proposed improved one. This improved `<system_error2>`
was then proposed as [the standard library support for Zero overhead exceptions as proposed
`std::error`](http://wg21.link/P1028).
A flurry of papers and discussion then resulted, running up to the Prague 2020 WG21
meeting where WG21 liked the library part of deterministic exceptions i.e. `std::error`,
and wanted to see a working implementation of a compiler implementing the language
part before moving further. The covid pandemic then ceased face to face meetings which
deeply impacted WG21 productivity, so everything large which was not yet approved for
entry into C++ 23 went on pause.
## Outcome v2.2 (2021)
Outcome was sufficiently popular, and widely known as the closest simulacrum of deterministic
exceptions currently available in C++, that it was regularly benchmarked as such on an 'as if'
basis by a number of people in the wider C++ ecosystem, including comparing their 'better Outcome
alternatives' to Outcome, where invariably Outcome appeared to lose badly in various
synthetic tests. Whilst any empirical measurements in the real world code never showed
a statistically significant difference, it was certainly true that v2.1's codegen in
assembler was not ideal.
On the behalf of WG21, Ben Craig did some benchmarking work on Outcome v2.1 in [P1886 *Error speed benchmarking*](https://wg21.link/P1886),
where it did not perform as well as expected compared to alternatives such as returning
a simple integer from a function. This led to a
[`better_optimisation`](https://github.com/ned14/outcome/tree/better_optimisation) branch.
The changes were felt worth merging into Outcome as v2.2.0, the first major version release
since Outcome entered Boost in early 2019. To give enough time to sign post to users that these
source incompatible changes were coming, all of 2020 was given over to announcement of the
upcoming merge of the breaking v2.2 branch into master branch in early 2021.
In terms of codegen benefits for proposed `std::error` based code (i.e. code using
[Outcome experimental]({{< relref "/experimental" >}})), v2.2 implements a library-based
emulation of [P1029 *move = bitcopies*](https://wg21.link/P1029), a proposed compiler
enhancement which can treat some move-only types as bags of bits. This very significantly
improves the appearance in assembler of experimental Outcome based code.
## Outcome v2.2.3 (2022)
Outcome v2.2 saw much popularity and very few issues reported after a year in the wild,
so the decision was taken [to write the v2.2.3 Outcome ABI into stone]({{% relref "/abi-stability" %}}) going forward.
This is the guarantee that binaries compiled with the v2.2.3 release will link and work
without issue with binaries compiled with any later version of Outcome.
This pretty much draws a line under further significant development of Outcome -- it
has now effectively entered 'sustaining', as big multinationals would term it i.e.
only small bug fixes and maintenance for future toolchains and languages etc would
be expected going forth from now.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/exceptions.md | +++
title = "std exception throws"
description = "Advantages and disadvantages of C++ exception throws"
weight = 10
+++
(Note that we assume a table-based EH implementation here, a SJLJ EH implementaton would have even happy and sad path runtime overhead. Table-based EH implementations are almost universal on x64, ARM and AArch64 targets).
C++ exception throws came in the original C++ 98 standard -- at that time, not all the major compilers implemented them yet, and several of those who did did not have efficient implementations, plus in the original days some compiler vendors still patented things like EH implementation techniques to try and maintain a competitive advantage over rival compilers. Unlike other C++ features, enabling C++ exceptions on a code base not written with them in mind is not safe, so this led to the C++ ecosystem becoming bifurcated into exceptions-enabled and exceptions-disabled camps.
#### Pros:
- Zero runtime overhead on the happy path.
- Success-orientated syntax declutters code of failure control flow paths.
- As a built-in language feature, probably has the least impact on optimisation of any failure handling mechanism here.
- Ships with every standard toolchain (though may not work in some, and cannot be safely enabled for many codebases).
#### Cons:
- Unpredictable runtime overhead on the sad path.
- Unacceptable runtime overhead on the sad path for real time applications.
- Adds considerable bloat to produced binaries, which can be unacceptable for some use cases (embedded).
- Requires RTTI to be enabled or non-standard behaviour results (which is further binary bloat).
- Not available by tradition or convention in several major parts of the C++ ecosystem (embedded, games, audio, to a lesser extent financial).
- Not available in many niche architectures such as HPC, GPUs, DSPs and microcontrollers.
- Most codebases do not invest in adequate correctness testing of the silent proliferation of failure control flow paths which result in C++ exception throwing code (exception throws silently generate multitudes of slight variations of sad path control flows).
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/_index.md | +++
title = "Review of Error Handling Frameworks"
weight = 8
+++
Outcome [started life in 2014]({{% relref "/history" %}}), entered Boost as Boost.Outcome in 2018, and therefore was amongst the very first of the major alternative error handling frameworks to standard exception throws in C++. Since then, and sometimes in reaction to Outcome's choice of design, alternative frameworks have appeared. This page tries to give a fairly even handed summary of those alternatives, and how they compare to Outcome in this author's opinion.
These are listed in order of approximate availability to the C++ ecosystem i.e. in order of appearance.
{{% children description="true" depth="2" %}}
My thanks to Emil Dotchevski for reviewing this summary and providing notes.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/outcome.md | +++
title = "Outcome (proposed std result)"
description = "Advantages and disadvantages of Outcome and its proposed `std::result<T>`"
weight = 40
+++
Outcome (the library described by this documentation) originated in a negative reaction to then originally proposed `std::expected<T, E>`, though what got eventually standardised as `std::expected<T, E>` looks much more like Outcome's `result<T, E>` than the original Expected. [You can read here how those experiences led me to develop Outcome v1]({{% relref "/history" %}}). Outcome comes in both standalone and Boost editions, and its current design was completed in 2018.
Outcome's core is two workhorse types and a macro:
- {{% api "basic_result<T, E, NoValuePolicy>" %}}
- {{% api "basic_outcome<T, EC, EP, NoValuePolicy>" %}}
- {{% api "OUTCOME_TRY(var, expr)" %}}
These three core items are then mixed into a veritable cornucopia of [convenience typedefs]({{% relref "/reference/aliases" %}}) and variations to support a wide range of use cases, including [in C++ coroutines]({{% relref "/tutorial/essential/coroutines" %}}), plus there is extensive plumbing and customisation points for deciding how incompatible types ought to interact, or being notified of lifecycle events (e.g. capture a stack backtrace if a `result<T, E>` is constructed with an error).
Outcome perfectly propagates constexpr, triviality and `noexcept`-ness of each individual operation of the types you configure it with. It never touches dynamic memory allocation, and it has been carefully written so the compiler will optimise it out of codegen entirely wherever that is possible. It is capable of 'true moves' for types which declare themselves 'move bitcopying compatible' i.e. destructor calls on moved-from values are elided. 'True moves' can have a game changing performance gain on types with virtual destructors.
Outcome takes a lot of care to have the least possible impact on build times, and it guarantees that a binary built with it will have stable ABI so it is safe to use in _really_ large C++ codebases (standalone edition only). For interoperation with other languages, it guarantees that C code can work with Outcome data types, and it provides a C macro API header file to help with that.
Outcome recognises Expected-like types and will construct from them, which aids interoperability. [A simplified Result type is proposed for standardisation as `std::result<T>`](https://wg21.link/P1028) where the `E` type is hard coded to a proposed `std::error`. This proposed standardisation has been deployed on billions of devices at the time of writing, and [you can use it today via Experimental.Outcome]({{% relref "/experimental" %}}), the reference implementation.
#### Pros:
- Predictable runtime overhead on the happy path.
- Predictable runtime overhead on the sad path.
- Very little codegen bloat added to binaries (though there is a fixed absolute overhead for support libraries if you use Outcome's bundled error types).
- Neither success nor failure is prioritised during use -- types will implicitly construct from both `T` and `E` if it is unambiguous, so no clunky added markup needed to return an `E`.
- Sad path control flow is required to be explicitly specified in every situation. This significantly reduces the number of sad control flow paths in a code base, making it much easier to test all of them. It also means that sad paths get audited and checked during code reviews.
- Macro `TRY` operator feels a bit unnatural to use, but is a god send to saving visual code clutter when all you want to say is 'handle this failure by asking my caller to handle it'. It also works with non-Outcome types, and has its own suite of customisation points for third party extension.
- Works well in all configurations of C++, including C++ exceptions and RTTI globally disabled.
- Works well on all niche architectures, such as HPC, GPUs, DSPs and microcontrollers, and does not dynamically allocate memory.
#### Cons:
- Sad path control flow is required to be explicitly specified in every situation. For code where failure is extremely unlikely, or is not important because it always results in aborting the current operation, the added visual code clutter is unhelpful.
- Results in branchy code, which is slow -- though predictably so -- for embedded controller CPUs.
- Failure to examine an Outcome type generates a compiler diagnostic, but failure to handle both failure and success does not. This can mean failures or successes get accidentally dropped.
- To prevent variant storage having an outsize impact on build times in the same way widespread use of `std::variant` has, Outcome only implements union storage when both `T` and `E` are trivially copyable or move bitcopying. Otherwise struct storage is used, which means Outcome's types are larger than Expected's. This is because implementing exception guarantees during copies and moves of non-trivially-copyable types in union storage involves a lot of work for the compiler on every use of copy and move, so by using struct storage Outcome reduces build time impact from copies and moves significantly.
Note that one of the major uses of Outcome types is as the return type from a function, in which case copy elision would happen in C++ 14 and is guaranteed from C++ 17 onwards. This means that the larger footprint of struct storage typically has much less impact in optimised code than might be the case if you store these types inside other types.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/expected.md | +++
title = "std expected"
description = "Advantages and disadvantages of `std::expected<T, E>`"
weight = 30
+++
`std::expected<T, E>` came originally from an experimental monadic and generic programming library outside of Boost written by Boost and WG21 developers around 2013. Before Outcome v1, I deployed the then Expected into a large codebase and I was dismayed with the results, especially on build times. [You can read here how those experiences led me to develop Outcome v1]({{% relref "/history" %}}).
`std::expected<T, E>` is a constrained variant type with a strong preference for the successful type `T` which it models like a `std::optional<T>`. If, however, there is no `T` value then it supplies an 'unexpected' `E` value instead. `std::expected<T, E>` was standardised in the C++ 23 standard.
Outcome's Result type [can be configured to act just like Expected if you want that]({{% relref "/faq#how-far-away-from-the-proposed-std-expected-t-e-is-outcome-s-checked-t-e" %}}), however ultimately [Outcome's Result doesn't solve the same problem as Expected]({{% relref "/faq#why-doesn-t-outcome-duplicate-std-expected-t-e-s-design" %}}), plus Outcome models `std::variant<T, E>` rather than `std::optional<T>` which we think much superior for many use cases, which to summarise:
- If you are parsing input which may rarely contain unexpected values, Expected is the right choice here.
- If you want an alternative to C++ exception handling i.e. a generalised whole-program error handling framework, Expected is an inferior choice to alternatives.
Outcome recognises Expected-like types and will construct from them, which aids interoperability.
#### Pros:
- Predictable runtime overhead on the happy path.
- Predictable runtime overhead on the sad path.
- Very little codegen bloat added to binaries (though there is a fixed absolute overhead for support libraries).
- Variant storage means storage overhead is minimal, except when either `T` or `E` has a throwing move constructor which typically causes storage blowup.
- Works well in all configurations of C++, including C++ exceptions and RTTI globally disabled.
- Works well on all niche architectures, such as HPC, GPUs, DSPs and microcontrollers.
- Ships with every standard library since C++ 23.
#### Cons:
- Success-orientated syntax makes doing anything with the `E` type is awkward and clunky.
- Results in branchy code, which is slow -- though predictably so -- for embedded controller CPUs.
- Failure to examine an Expected generates a compiler diagnostic, but failure to handle both failure and success does not. This can mean failures or successes get accidentally dropped.
- Lack of a `try` operator makes use tedious and verbose.
- Variant storage does have an outsize impact on build times in the same way widespread use of `std::variant` has. This is because implementing exception guarantees during copies and moves of non-trivially-copyable types in union storage involves a lot of work for the compiler on every use of copy and move.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/error_code.md | +++
title = "std error codes"
description = "Advantages and disadvantages of `std::error_code`"
weight = 20
+++
`std::error_code` came originally from `boost::error_code` which was designed around 2008 as part of implementing Filesystem and Networking. They are a simple trivially copyable type offering improved type safety and functionality over C enumerations. [You can read more about how `std::error_code` works here]({{% relref "/motivation/std_error_code" %}}). They were standardised in the C++ 11 standard, and have been available in Boost since 2008.
#### Pros:
- Predictable runtime overhead on the happy path.
- Predictable runtime overhead on the sad path.
- Unbiased syntax equal for both success and failure requiring explicit code written to handle both.
- Very little codegen bloat added to binaries (though there is a fixed absolute overhead for support libraries).
- Once constructed, passing around `std::error_code` instances optimises well, often being passed in CPU registers.
- Works well in all configurations of C++, including C++ exceptions and RTTI globally disabled.
- Works well on all niche architectures, such as HPC, GPUs, DSPs and microcontrollers.
- Ships with every standard library since C++ 11.
#### Cons:
- Failure to write handling code for failure means failures get silently dropped. This is disturbingly easy to do.
- Results in branchy code, which is slow -- though predictably so -- for embedded controller CPUs.
- Because the `std::error_category` instance used in construction comes from a magic static, the compiler inserts an atomic operation around every `std::error_code` construction (e.g. https://godbolt.org/z/oGaf4qe8a). This can impact optimisation on compilers with poor optimisation of atomics.
- The payload of type `int` is incredibly constraining sometimes, especially on 64-bit platforms. It would have been much better if it were `intptr_t` instead of `int`.
- The payload value of all bits zero has silent hard coded semantics which is incompatible with many C enumerations, which start from value zero. This can cause silent dropping of failures in a very hard to debug way.
- How comparisons between disparate code categories (i.e. mapping) is supposed to work is non-obvious, and even standard library maintainers and many members of WG21 have been confused by it in the past.
(Note that this long list of design caveats is what led to the proposed superseding of `std::error_code` with `std::error`, which you can use today in Outcome.Experimental. See [this page for more information]({{% relref "/experimental" %}})). |
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/alternatives/leaf.md | +++
title = "LEAF"
description = "Advantages and disadvantages of Lightweight Error Augmentation Framework"
weight = 50
+++
As much as Outcome originated in a negative reaction to the then originally proposed `std::expected<T, E>`, [LEAF](https://boostorg.github.io/leaf/) originated in a negative reaction to Outcome. Some of the perceived issues with Outcome were ([LEAF's own rendition of this can be viewed here](https://boostorg.github.io/leaf/#rationale)):
- Outcome based code is visually cluttered, as both happy and sad paths appear in code.
- Outcome based code generates branchy code at runtime, which impacts low end CPUs and first time code execution.
- Outcome's Result type encodes the type of the error in the function signature, which could be considered as more brittle and problematic for large scale code refactoring[^1].
- Outcome is more strongly opinionated about being the ultimate error handling framework in a program (i.e. all third party custom error handling is assumed to flow into Outcome via customisation point adapters), whereas LEAF is less strongly opinionated, and yet provides equivalent functionality.
LEAF therefore looks more like standard C++ exception handling, but without the non-deterministic sad path at the cost of a slight impact on happy path runtime performance. LEAF's current design was completed in 2020.
If you need an error handling framework which has predictable sad path overhead unlike C++ exceptions, but you otherwise want similar syntax and use experience to C++ exceptions, LEAF is a very solid choice.
#### Pros:
- Very low runtime overhead on the happy path.
- Very low runtime overhead on the sad path.
- Does not cause branchy code to the same extent as Outcome, and the sad path is deterministic unlike with C++ exceptions.
- Very little codegen bloat added to binaries (though there is a fixed absolute overhead for support libraries, most of which can be compiled out using a macro if desired).
- Unlike with any of the preceding options, failures nor successes cannot get unintentionally dropped. This is the same strength of guarantee as with C++ exceptions.
- Works well in most configurations of C++, including C++ exceptions and RTTI globally disabled. Does not dynamically allocate memory.
#### Cons:
- Requires out of band storage for state e.g. thread local storage, or a global synchronised ring buffer[^2].
- If thread local storage is chosen as the out of band storage, transporting LEAF state across threads requires manual intervention.
- If a global ring buffer is chosen as the out of band storage, thread synchronisation with global state is required and the ring buffer can wrap which drops state.
- Thread local storage can be problematic or even a showstopper in many niche architectures such as HPC, GPUs, DSPs and microcontrollers. Global synchronised state can introduce an unacceptable performance impact on those architectures.
- Current compilers at the time of writing do not react well to use of thread local storage, it would seem that elision of code generation is inhibited if thread local state gets touched due to pessimistic assumptions about escape analysis. Given that this impacts all of C and C++ due to the same problem with `errno`, it is hoped that future compilers will improve this. Until then, any code which touches thread local storage or magic statics[^3] will not optimise as well as code which does neither.
[^1]: In Outcome, it is strongly recommended that one chooses a single universal error type for all public APIs such as `std::error_code` or `error` from Experimental.Outcome, so if the programmer is disciplined then the function signature does not expose internal error types. Such single universal error types type erase the original error object, but still allow the original error object to be inspected. This avoids 'exception specifications' which are widely known to not scale well.
[^2]: A global synchronised ring buffer implementation does not ship with LEAF, however LEAF exposes customisation points for a bespoke thread local storage implementation which makes implementing one very straightforward.
[^3]: `std::error_code` construction touches a magic static or calls an extern function, and therefore Outcome when combined with `std::error_code` also sees a codegen pessimisation. Experimental Outcome's `error` fixes this historical oversight.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/exceptions.md | +++
title = "Exceptions"
description = "Exceptions with their good and bad sides."
weight = 10
+++
Exceptions are the default mechanism in C++ for reporting, propagating and
processing the information about function failures. Their main advantage is
the ability to describe the "success dependency" between functions: if you want to
say that calling function `g()` depends on the successful execution of function `f()`,
you just put `g()` below `f()` and that's it:
```c++
int a()
{
f();
g(); // don't call g() and further if f() fails
return h(); // don't call h() if g() fails
}
```
In the C++ Standard terms this means that `f()` is *sequenced before* `g()`.
This makes failure handling extremely easy: in a lot of cases you do not have
to do anything.
Also, while next operations are being canceled, the exception object containing
the information about the initial failure is kept on the side. When at some point
the cancellation cascade is stopped by an exception handler, the exception object
can be inspected. It can contain arbitrarily big amount of data about the failure
reason, including the entire call stack.
### Downsides
There are two kinds of overheads caused by the exception handling mechanism. The
first is connected with storing the exceptions on the side. Stack unwinding works
independently in each thread of execution; each thread can be potentially handling
a number of exceptions (even though only one exception can be active in one thread).
This requires being prepared for storing an arbitrary number of exceptions of arbitrary
types per thread. Additional things like jump tables also need to be stored in the
program binaries.
Second overhead is experienced when throwing an exception and trying to find the
handler. Since nearly any function can throw an exception of any time, this is
a dynamic memory allocation. The type of an exception is erased and a run-time type
identification (RTTI) is required to asses the type of the active exception object.
The worst case time required for matching exceptions against handlers cannot be easily
predicted and therefore exceptions are not suitable for real-time or low-latency
systems.
Another problem connected with exceptions is that while they are good for program
flows with linear "success dependency", they become inconvenient in situations where
this success dependency does not occur. One such notable example is releasing acquired
resources which needs to be performed even if previous operations have failed.
Another example is when some function `c()` depends on the success of at least one
of two functions `a()` and `b()` (which try, for instance, to store user data by
two different means), another example is when implementing a strong exception safety
guarantee we may need to apply some fallback actions when previous operations have
failed. When failures are reported by exceptions, the semantics of canceling all
subsequent operations is a hindrance rather than help; these situations require special
and non-trivial idioms to be employed.
For these reasons in some projects using exceptions is forbidden. Compilers offer
switches to disable exceptions altogether (they refuse to compile a `throw`, and turn
already compiled `throw`s into calls to `std::abort()`).
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/plug_error_code.md | +++
title = "Plugging a library into `std::error_code`"
description = "Illustrates how you can hook into the `std::error_code` system from the Standard Library in order to work with your own set of error codes."
weight = 50
+++
[See here for this guide, but for `boost::system::error_code`]({{% relref "plug_error_code2" %}}).
This section illustrates how you can hook into the `std::error_code` system from
the Standard Library in order to work with your own set of error codes. As is usually
the case in C++, doing this is straightforward but requires typing boilerplate
to tell the C++ STL about your custom error type. This is not part of Outcome library,
but we still provide this short guide here, because how to do this is not well documented [1].
Suppose you want to report all reasons for failure in converting a `std::string` to a non-negative `int`.
The list is:
* `EmptyString` -- the input string is empty,
* `IllegalChar` -- input contains characters that are not digits,
* `TooLong` -- input represents a number, but this number would not fit into a variable of type `int`.
{{% snippet "error_code_registration.cpp" "error_code_registration" %}}
This might look like a lot of extra boilerplate over simply using your custom
error code enum directly, but look at the advantages:
1. Any code which can speak `std::error_code` can now work with errors from your
code, AND without being recompiled.
2. `std::system_error` can now wrap your custom error codes seamlessly, allowing
your custom error code to be converted into a C++ exception *and back out again*
without losing information.
3. `std::error_code` knows how to print itself, and will print your custom error
code without extra work from you. As usually you'd need to define a print routine
for any custom error code you'd write anyway, there is actually very little extra
boilerplate here.
4. If you implement the `default_error_condition()` override, you can allow code
exclusively written to understand `std::errc` alone to examine your custom error
code domain for equivalence to the standard error conditions, AND without being
recompiled.
{{% notice note %}}
This documentation recommends that when you define your custom `enum` for representing
`error_code`s, you should always make sure that value 0 never represents an actual error:
it should either represent a success or should not be provided at all. If you only
intend to use your `enum` inside `result<>` or `outcome<>` you can just start your
enumerations from 1. If you intend to also return `std::error_code` directly from
functions, you should probably define value 0 as success, so that you are able to
inform about function's success by returning `MyEnum::Success`. This is because `error_code`'s
contextual conversion to `bool` (which some people use to check if there was an error or not)
only checks for the numeric value of the error code (without looking at error domain (category)).
{{% /notice %}}
[1]: The only documentation I'm aware of is the quite old guide by Chris Kohlhoff, founder of ASIO and the Networking TS:
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-1.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-2.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-3.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-4.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-5.html
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/error_codes.md | +++
title = "Error codes"
description = "Error codes with their good and bad sides."
weight = 30
+++
Error codes are reasonable error handling technique, also working in C.
In this case the information is also stored as an `int`, but returned by value,
which makes it possible to make functions pure (side-effect-free and referentially
transparent).
```c++
int readInt(const char * filename, int& val)
{
FILE* fd;
int r = openFile(filename, /*out*/ fd);
if (r != 0)
return r; // return whatever error openFile() returned
r = readInt(fd, /*out*/ val);
if (r != 0)
return READERRC_NOINT; // my error code
return 0; // success
}
```
Because the type of the error information (`int`) is known statically, no memory
allocation or type erasure is required. This technique is very efficient.
### Downsides
All failure paths written manually can be considered both an advantage and a
disadvantage. Forgetting to put a failure handling `if` causes bugs.
If I need to substitute an error code returned by lower-level function with mine
more appropriate at this level, the information about the original failure is
gone.
Also, all possible error codes invented by different programmers in different
third party libraries must fit into one `int` and not overlap with any other error
code value. This is quite impossible and does not scale well.
Because errors are communicated through returned values, we cannot use function's
return type to return computed values. Computed values are written to function
*output* parameters, which requires objects to be created before we have values
to put into them. This requires many objects in unintended state to exist. Writing
to output parameters often requires an indirection and can incur some run-time cost.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/_index.md | +++
title = "Motivation"
weight = 8
+++
This section describes techniques currently used to report and handle failures
in functions, it also shows why these techniques might be insufficient.
If you just want to learn how to use Outcome library go straight to [Tutorial
section]({{% relref "/tutorial" %}}).
{{% notice note %}}
Motivation section of this documentation is not complete yet.
{{% /notice %}}
{{% children description="true" depth="1" %}}
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/errno.md | +++
title = "errno"
description = "errno with their good and bad sides."
weight = 20
+++
The idiom of returning, upon failure, a special value and storing an error code
(an `int`) inside a global (or thread-local) object `errno` is inherited from C,
and used in its Standard Library:
```c++
int readValue(const char * filename)
{
FILE* f = fopen(filename, "r");
if (f == NULL)
return 0; // special value indicating failure
// keep errno value set by fopen()
int i;
int r = fscanf(f, "%d", &i);
if (r == 0 || r == EOF) { // special values: i not read
errno = ENODATA; // choose error value to return
return 0;
fclose(f);
errno = 0; // clear error info (success)
return i;
}
```
One advantage (to some, and a disadvantage to others) of this technique is that it
uses familiar control statements (`if` and `return`) to indicate all execution
paths that handle failures. When we read this code we know when and under what
conditions it can exit without producing the expected result.
### Downsides
Because on failure, as well as success, we write into a global (or thread-local)
object, our functions are not *pure*: they have *side effects*. This means many
useful compiler optimizations (like common subexpression elimination) cannot be
applied. This shows that it is not only C++ that chooses suboptimal solutions
for reporting failures.
Whatever type we return, we always need a special value to spare, which is
sometimes troublesome. In the above example, if the successfully read value of
`i` is `0`, and we return it, our callers will think it is a failure even though
it is not.
Error propagation using `if` statements and early `return`s is manual. We can easily
forget to check for the failure, and incorrectly let the subsequent operations
execute, potentially causing damage to the program state.
Upon nearly each function call layer we may have to change error code value
so that it reflects the error condition adequate to the current layer. If we
do so, the original error code is gone.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/plug_error_code2.md | +++
title = "Plugging a library into `boost::system::error_code`"
description = "Illustrates how you can hook into the `boost::system::error_code` system from Boost in order to work with your own set of error codes."
weight = 55
+++
[See here for this guide, but for `std::error_code`]({{% relref "plug_error_code" %}}).
This section illustrates how you can hook into the `boost::system::error_code` system from
the Boost in order to work with your own set of error codes. As is usually
the case in C++, doing this is straightforward but requires typing boilerplate
to tell Boost.System about your custom error type. This is not part of Outcome library,
but we still provide this short guide here, because how to do this is not well documented [1].
Suppose you want to report all reasons for failure in converting a `std::string` to a non-negative `int`.
The list is:
* `EmptyString` -- the input string is empty,
* `IllegalChar` -- input contains characters that are not digits,
* `TooLong` -- input represents a number, but this number would not fit into a variable of type `int`.
{{% snippet "boost-only/error_code_registration.cpp" "error_code_registration" %}}
This might look like a lot of extra boilerplate over simply using your custom
error code enum directly, but look at the advantages:
1. Any code which can speak `boost::system::error_code` can now work with errors from your
code, AND without being recompiled.
2. `boost::system::system_error` can now wrap your custom error codes seamlessly, allowing
your custom error code to be converted into a C++ exception *and back out again*
without losing information.
3. `boost::system::error_code` knows how to print itself, and will print your custom error
code without extra work from you. As usually you'd need to define a print routine
for any custom error code you'd write anyway, there is actually very little extra
boilerplate here.
4. If you implement the `default_error_condition()` override, you can allow code
exclusively written to understand `boost::system::errc` alone to examine your custom error
code domain for equivalence to the standard error conditions, AND without being
recompiled.
{{% notice note %}}
This documentation recommends that when you define your custom `enum` for representing
`error_code`s, you should always make sure that value 0 never represents an actual error:
it should either represent a success or should not be provided at all. If you only
intend to use your `enum` inside `result<>` or `outcome<>` you can just start your
enumerations from 1. If you intend to also return `boost::system::error_code` directly from
functions, you should probably define value 0 as success, so that you are able to
inform about function's success by returning `MyEnum::Success`. This is because `error_code`'s
contextual conversion to `bool` (which some people use to check if there was an error or not)
only checks for the numeric value of the error code (without looking at error domain (category)).
{{% /notice %}}
[1]: The only documentation I'm aware of is the quite old guide by Chris Kohlhoff, founder of ASIO and the Networking TS:
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-1.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-2.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-3.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-4.html
- http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-5.html
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/std_error_code.md | +++
title = "std::error_code"
description = "Overview of std::error_code"
weight = 40
+++
Type `std::error_code` has been designed to be sufficiently small and trivial
to be cheaply passed around, and at the same time be able to store sufficient
information to represent any error situation from any library/sub-system in the
world without a clash. Its representation is basically:
```c++
class error_code
{
error_category* domain; // domain from which the error originates
int value; // numeric value of error within the domain
};
```
Here, `domain` indicates the library from which the error originates. It is a
pointer to a global object representing a given library/domain. Different
libraries will be represented by different pointers to different globals.
Each domain is expected to be represented by a global object derived from
`std::error_category`. The uniqueness of the domain pointer value is guaranteed
by the uniqueness of addresses of different global objects.
Now, `value` represents a numeric value of a particular error situation within
the domain. Thus, different domains can use the same numeric value `1` to
indicate different error situations, but two `std::error_code` objects will be
different because the pointers representing domains will be different.
`std::error_code` comes with additional tools: a facility for defining custom
domains with their set of error codes, and a facility for building predicates
that allow classifying errors.
Once created and passed around (either inside a thrown exception or returned from functions by value) there is never a need to change the value of `error_code`
object at any level. But at different levels one can use different predicates
for classifying error situations appropriately to the program layer.
When a new library needs to represent its own set of error situations in an
`error_code` it first has to declare the list of numeric value as an enumeration:
```c++
enum class ConvertErrc
{
StringTooLong = 1, // 0 should not represent an error
EmptyString = 2,
IllegalChar = 3,
};
```
Then it has to put some boiler-plate code to plug the new enumeration into the
`std::error_code` system. Then, it can use the enum as an `error_code`:
```c++
std::error_code ec = ConvertErrc::EmptyString;
assert(ec == ConvertErrc::EmptyString);
```
Member `value` is mapped directly from the numeric value in the enumeration, and
member `domain` is mapped from the type of the enumeration. Thus, this is a form
of type erasure, but one that does allow type `std::error_code` to be trivial
and standard-layout.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/motivation/narrow_contract.md | +++
title = "Narrow contracts"
description = "Describes narrow-contract functions that do not work for all input values, and advantage of using them."
weight = 60
+++
A program's thread of execution can enter a "disappointing" state for two reasons:
* due to disappointing situation in the environment (operating system, external input),
or
* due to a bug in the program.
The key to handling these disappointments correctly is to identify to which
category they belong, and use the tools adequate for a given category. In this
tutorial when we say "error" or "failure" we only refer to the first category.
A bug is not an error.
A bug is when a program is something else than what it is supposed to be. The
correct action in that case is to change the program so that it is exactly what
it is supposed to be. Unfortunately, sometimes the symptoms of a bug are only
detected when the system is running and at this point no code changes are possible.
In contrast, a failure is when a correct function in a correct program reflects
some disappointing behavior in the environment. The correct action in that case
is for the program to take a control path different than usual, which will likely
cancel some operations and will likely result in different communication with the
outside world.
Symptoms of bugs can sometimes be detected during compilation or static program
analysis or at run-time when observing certain values of objects that are declared
never to be valid at certain points. One classical example is passing a null pointer
to functions that expect a pointer to a valid object:
```c++
int f(int * pi) // expects: pi != nullptr
{
return *pi + 1;
}
```
Passing a null pointer where it is not expected is so common a bug that tools
are very good at finding them. For instance, static analyzers will usually detect
it without even executing your code. Similarly, tools like undefined behavior
sanitizers will compile a code as the one above so that a safety check is performed
to check if the pointer is null, and an error message will be logged and program
optionally terminated.
More, compilers can perform optimizations based on undefined behavior caused by
dereferencing a null pointer. In the following code:
```c++
pair<int, int> g(int * pi) // expects: pi != nullptr
{
int i = *pi + 1;
int j = (pi == nullptr) ? 1 : 0;
return {i, j};
}
```
The compiler can see that if `pi` is null, the program would have undefined
behavior. Since undefined behavior is required by the C++ standard to never
be the programmer's intention, the compiler
assumes that apparently this function is never called with `pi == nullptr`. If so,
`j` is always `0` and the code can be transformed to a faster one:
```c++
pair<int, int> g(int * pi) // expects: pi != nullptr
{
int i = *pi + 1;
int j = 0;
return {i, j};
}
```
Functions like the one above that declare that certain values of input parameters
must not be passed to them are said to have a *narrow contract*.
Compilers give you non-standard tools to tell them about narrow contracts, so
that they can detect it and make use of it the same way as they are detecting
invalid null pointers. For instance, if a function in your library takes an `int`
and declares that the value of this `int` must never be negative. You can use
`__builtin_trap()` available in GCC and clang:
```c++
void h(int i) // expects: i >= 0
{
if (i < 0) __builtin_trap();
// normal program logic follows ...
}
```
This instruction when hit, causes the program to exit abnormally, which means:
* a debugger can be launched,
* static analyzer can warn you if it can detect a program flow that reaches this
point,
* UB-sanitizer can log error message when it hits it.
Another tool you could use is `__builtin_unreachable()`, also available in GCC
and clang:
```c++
void h(int i) // expects: i >= 0
{
if (i < 0) __builtin_unreachable();
// normal program logic follows ...
}
```
This gives a hint to the tools: the programmer guarantees that the program flow
will never reach to the point of executing it. In other words, it is undefined
behavior if control reaches this point. Compiler and other tools can take this
for granted. This way they can deduce that expression `i < 0` will never be true,
and they can further use this assumption to issue warnings or to optimize the code.
UB-sanitizers can use it to inject a log message and terminate if this point is
nonetheless reached.
Allowing for some input values to be invalid works similarly to cyclic redundancy
checks. It allows for the possibility to observe the symptoms of the bugs (not
the bugs themselves), and if the symptom is revealed the hunt for the bug can start.
This is not only tools that can now easily detect symptoms of bugs, but also
humans during the code review. A reviewer can now say, "hey, function `h()` is
expecting a non-negative value, but this `i` is actually `-1`; maybe you wanted
to pass `j` instead?".
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/build/_index.md | +++
title = "Build and install"
weight = 3
+++
## Usage as a single header file
Outcome v2 comes in single header file form. This is regenerated per commit. To fetch
on Linux:
```
wget https://github.com/ned14/outcome/raw/master/single-header/outcome.hpp
```
On BSD:
```
fetch https://github.com/ned14/outcome/raw/master/single-header/outcome.hpp
```
If you have `curl` installed:
```
curl -O -J -L https://github.com/ned14/outcome/raw/master/single-header/outcome.hpp
```
Otherwise, simply download the raw file from above and place it wherever it suits you.
If you might be debugging using Microsoft Visual Studio, you may find the debugger
visualisation file at https://github.com/ned14/outcome/raw/master/include/outcome/outcome.natvis
useful to include into your build.
## Usage from the vcpkg package manager
This is particularly easy, and works on Mac OS, Linux and Microsoft Windows:
```
vcpkg install outcome
```
Outcome appears at `<outcome/outcome.hpp>`. This is a full copy of Outcome, so
Experimental Outcome and all the usual headers are where you would expect.
## Usage from the Conan package manager
*(thanks to Théo Delrieu for contributing this support)*
At the command line, add the bintray repo for Outcome to conan:
```
conan remote add outcome https://api.bintray.com/conan/ned14/Outcome
```
Now simply add this to your Conan build:
```
[requires]
Outcome/master@ned14/stable
```
Outcome will be made available by Conan at `<outcome.hpp>`.
## Usage from the cmake hunter package manager
Outcome has not been submitted to the main cmake hunter package manager repo yet.
You can however add it as a git submodule:
```
cd yourthirdpartyrepodir
git submodule add https://github.com/ned14/quickcpplib
git submodule add https://github.com/ned14/outcome
cd ..
git submodule update --init --recursive
```
Now tell cmake hunter about a git submoduled cmake hunter package by
adding to your project's `cmake/Hunter/config.cmake`:
```
hunter_config(quickcpplib GIT_SUBMODULE "yourthirdpartyrepodir/quickcpplib")
hunter_config(outcome GIT_SUBMODULE "yourthirdpartyrepodir/outcome")
```
... and finally to your `CMakeLists.txt`, now add outcome as if it were
an ordinary cmake hunter package:
```
hunter_add_package(quickcpplib)
find_package(quickcpplib CONFIG REQUIRED)
hunter_add_package(outcome)
find_package(outcome CONFIG REQUIRED)
```
Now you tell cmake to link to outcome as usual (see below for cmake targets):
```
target_link_libraries(mytarget outcome::hl)
```
## Usage as a git submodule
If you are very keen on tracking very latest Outcome, you can add it as a git
submodule to your project so you can keep abreast of bug fixes. Here is how:
```
git submodule add https://github.com/ned14/outcome
cd outcome
git checkout master
git submodule update --init --recursive
```
After this you can bring Outcome into your code using:
```
#include "outcome/single-header/outcome.hpp"
```
That's it, you are ready to go. From time to time, you may wish to update to
latest:
```
cd outcome
git pull
git submodule update
```
## Usage as a stable source tarball
If you would prefer a single source tarball of the stable and develop branches
known to have had all unit tests passing on all platforms, containing all the
documentation, tests and sources, this can always be retrieved from:
https://github.com/ned14/outcome/releases
This tarball is automatically generated when Outcome fully compiles and passes
all unit tests on all platforms tested by the CIs. This currently includes:
- Linux: GCC 7.5, clang 9, clang 11
- MacOS: XCode 12
- Windows: VS2019.7
All unit tests are executed under the Address and Undefined Behaviour sanitisers.
It should be emphasised that newer compilers are not tested, so there is
an unlikely chance that the tarball may not work on a newer compiler.
<hr>
# Running the unit test suite
To run the unit test suite you will need cmake 3.3 or later installed.
```
mkdir build
cd build
cmake ..
cmake --build .
ctest
```
On some cmake generators (Visual Studio, Xcode) you may need to tell cmake build a configuration
like Release or Debug. Similarly, ctest needs to be told the same e.g.
```
mkdir build
cd build
cmake ..
cmake --build . --config Release
ctest -C Release
```
[Per commit, tests are run by Travis and uploaded to a CDash dashboard here](http://my.cdash.org/index.php?project=Boost.Outcome).
<hr>
# CMake `find_package()` imported targets support
Outcome fully complies with cmake install, so by installing Outcome, it can be
found by cmake's `find_package()`.
```
mkdir build
cd build
cmake ..
cmake --build .
sudo cmake --build . --target install
```
# Modular CMake build support
If you are using Outcome in a CMake project, Outcome is a "modular cmake" project
using only modern cmake 3 throughout. This lets you add the Outcome directory as a
cmake subdirectory with no unexpected consequence on the rest of your cmake. You will need
to be using cmake 3.3 or better.
```
add_subdirectory(
"${CMAKE_CURRENT_SOURCE_DIR}/outcome" # path to outcome source
"${CMAKE_CURRENT_BINARY_DIR}/outcome" # your choice of where to put binaries
EXCLUDE_FROM_ALL # please only lazy build outcome on demand
)
```
Outcome's cmake has the following useful products:
- `outcome::hl` (target): the Outcome header-only library. Add this to any
`target_link_libraries()` in your cmake to bring in Outcome as a header-only library. This will also
add to your link (via `PUBLIC`) any debugger visualisation support files, any system library
dependencies and also force all consuming executables to be configured with a minimum
of C++ 14 as Outcome requires a minimum of that.
- `outcome_TEST_TARGETS` (list): a list of targets which generate Outcome's test
suite. You can append this to your own test suite if you wish to run Outcome's test
suite along with your own.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/abi-stability/_index.md | +++
title = "Future ABI stability guarantees"
weight = 9
+++
At the end of December 2021, [as had been intended and signposted from the beginning of development]({{% relref "/history" %}}), standalone Outcome v2.2.3 locked its ABI such that any code built with this Outcome release shall link, without recompilation, with any code built with any future Outcome release. This means that going forth, you are guaranteed that if your library returns an `outcome::`{{% api "result<T, E = varies, NoValuePolicy = policy::default_policy<T, E, void>>" %}} or `outcome::`{{% api "outcome<T, EC = varies, EP = varies, NoValuePolicy = policy::default_policy<T, EC, EP>>" %}} from a public API, consumers of your library are guaranteed 100% compatibility with unrecompiled library binaries when using any future version of Outcome in consuming code.
This is a critical use case for many large scale production use cases in industry, and to my knowledge, no other Outcome-like alternative implements this guarantee at the time of writing[^1]. Note also that Boost.Outcome comes with no ABI guarantees, as the dependencies within Boost that Boost.Outcome uses do not have a stable ABI guarantee.
To ensure this guarantee going forth, a per commit CI step has been added which tests Outcome against the v2.2.3 ABI using these tools:
- [The ABI compliance checker](https://lvc.github.io/abi-compliance-checker/) (using its `abi-dumper` mode, not its translation unit parsing mode which is too brittle).
- [Sourceware's libabigail tooling](https://sourceware.org/libabigail/manual/libabigail-tools.html).
Both tools are independent of one another, and whilst they test using the same mechanism (DWARF debug info extracted from an unoptimised shared library object), they have different implementations.
#### ABI testing implementation notes
Outcome is a header only library, so to turn Outcome into a shared library suitable as input for these tools, we compile a dummy shared library which exports APIs which use Outcome. The coverage of that dummy shared library of Outcome is therefore what is actually ABI tested, rather than of Outcome itself. The dummy library locks the ABI for:
- `basic_result<trivial type, std::error_code, all policies>` (i.e. union storage layout)
- `basic_outcome<trivial type, std::error_code, trivial type, all policies>`
- `basic_result<non-trivial type, std::error_code, all policies>` (i.e. struct storage layout)
- `basic_outcome<non-trivial type, std::error_code, std::exception_ptr, all policies>`
- `bad_result_access_with<std::error_code>`
- `bad_outcome_access`
- `atomic_eager<int>`
- `atomic_eager<basic_result<trivial type, std::error_code, all policies>>`
- `atomic_eager<basic_result<non-trivial type, std::error_code, all policies>>`
- `atomic_lazy<int>`
- `atomic_lazy<basic_result<trivial type, std::error_code, all policies>>`
- `atomic_lazy<basic_result<non-trivial type, std::error_code, all policies>>`
- `eager<int>`
- `eager<basic_result<trivial type, std::error_code, all policies>>`
- `eager<basic_result<non-trivial type, std::error_code, all policies>>`
- `lazy<int>`
- `lazy<basic_result<trivial type, std::error_code, all policies>>`
- `lazy<basic_result<non-trivial type, std::error_code, all policies>>`
Obviously anything which any of these types touch in their implementation also gets locked in ABI, in so far as the ABI tool can deduce dependent types. If you examine the source code for the dummy shared library, you will see that we go out of our way to encode explicit lists of dependent types in template parameters, to ensure that the ABI tool definitely discovers everything.
{{% notice note %}}
Outcome.Experimental has no ABI guarantees, as WG21 LEWG is actively modifying its design as it approaches the C++ standard.
{{% /notice %}}
The following targets are tested for ABI stability:
1. GCC 7.5 with libstdc++ configured with the C++ 14 standard and x64 architecture.
2. GCC 9.3 with libstdc++ configured with the C++ 17 standard and x64 architecture.
At the time of writing, no POSIX implementation has guaranteed stability on its C++ 20 standard library ABI, so we do not test that.
There is currently no CI coverage of MSVC ABI stability. The ABI compliance checker can test MSVC binaries for ABI stability, however raising the ABI compliance checker on a Github Actions Windows test runner is quite a lot of work. Donations of sufficient test scripting would be welcome. Note that because the Windows and POSIX implementation is almost the same, ABI stability on POSIX will have strong impact on MSVC ABI stability i.e. MSVC ABI is unlikely to break, albeit without CI testing there are no guarantees.
[^1]: libstdc++ implements a strong ABI stability guarantee and thus any future `std::expected<T, E>` implementation it provides will be ABI stable. However Expected offers only a small subset of the functionality which `outcome::result<T, E>` provides.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/faq/_index.md | +++
title = "Frequently asked questions"
weight = 30
+++
{{% toc %}}
## Is Outcome safe to use in extern APIs?
Outcome is specifically designed for use in the public interfaces of multi-million
line codebases. `result`'s layout is hard coded to:
```c++
struct trivially_copyable_result_layout {
union {
value_type value;
error_type error;
};
unsigned int flags;
};
```
... if both `value_type` and `error_type` are `TriviallyCopyable`, otherwise:
```c++
struct non_trivially_copyable_result_layout {
value_type value;
unsigned int flags;
error_type error;
};
```
This is C-compatible if `value_type` and `error_type` are C-compatible. {{% api "std::error_code" %}}
is *probably* C-compatible, but its layout is not standardised (though there is a
normative note in the standard about its layout). Hence Outcome cannot provide a
C macro API for standard Outcome, but we can for [Experimental Outcome]({{< relref "/experimental/c-api" >}}).
## Does Outcome implement over-alignment?
Outcome propagates any over-alignment of the types you supply to it as according
to the layout specified above. Therefore the ordinary alignment and padding rules
for your compiler are used.
## Does Outcome implement the no-fail, strong or basic exception guarantee?
([You can read about the meaning of these guarantees at cppreference.com](https://en.cppreference.com/w/cpp/language/exceptions#Exception_safety))
If for the following operations:
- Construction
- Assignment
- Swap
... the corresponding operation in **all** of `value_type`, `error_type` (and
`exception_type` for `outcome`) is `noexcept(true)`, then `result` and
`outcome`'s operation is `noexcept(true)`. This propagates the no-fail exception
guarantee of the underlying types. Otherwise the basic guarantee applies for all
but Swap, under the same rules as for the `struct` layout type given above e.g.
value would be constructed first, then the flags, then the error. If the error
throws, value and status bits would be as if the failure had not occurred, same
as for aborting the construction of any `struct` type.
It is recognised that these weak guarantees may be unsuitable for some people,
so Outcome implements `swap()` with much stronger guarantees, as one can locally refine,
without too much work, one's own custom classes from `result` and `outcome` implementing
stronger guarantees for construction and assignment using `swap()` as the primitive
building block.
The core ADL discovered implementation of strong guarantee swap is {{% api "strong_swap(bool &all_good, T &a, T &b)" %}}.
This can be overloaded by third party code with custom strong guarantee swap
implementations, same as for `std::swap()`. Because strong guarantee swap may fail
when trying to restore input state during handling of failure to swap, the
`all_good` boolean becomes false if restoration fails, at which point both
results/outcomes get marked as tainted via {{% api "has_lost_consistency()" %}}.
It is **up to you** to check this flag to see if known good state has been lost,
as Outcome never does so on your behalf. The simple solution to avoiding having
to deal with this situation is to always choose your value, error and exception
types to have non-throwing move constructors and move assignments. This causes
the strong swap implementation to no longer be used, as it is no longer required,
and standard swap is used instead.
## Does Outcome have a stable ABI and API?
The layout changed for all trivially copyable types between Outcome v2.1 and v2.2,
as union based storage was introduced. From v2.2 onwards, the layout is not
expected to change again.
If v2.2 proves to be unchanging for 24 months, Outcome's ABI and API will be
formally fixed as **the** v2 interface and written into stone forever. Thereafter
the [ABI compliance checker](https://lvc.github.io/abi-compliance-checker/)
will be run per-commit to ensure Outcome's ABI and API remains stable. This is
currently expected to occur in 2022.
Note that the stable ABI and API guarantee will only apply to standalone
Outcome, not to Boost.Outcome. Boost.Outcome has dependencies on other
parts of Boost which are not stable across releases.
Note also that the types you configure a `result` or `outcome` with also need
to be ABI stable if `result` or `outcome` is to be ABI stable.
## Can I use `result<T, EC>` across DLL/shared object boundaries?
A known problem with using Windows DLLs (and to smaller extent POSIX shared libraries) is that global
objects may get duplicated: one instance in the executable and one in the DLL. This
behaviour is not incorrect according to the C++ Standard, as the Standard does not
recognize the existence of DLLs or shared libraries. Therefore, program designs that
depend on globals having unique addresses may become compromised when used in a program
using DLLs.
Nothing in Outcome depends on the addresses of globals, plus the guaranteed fixed data
layout (see answer above) means that different versions of Outcome can be used in
different DLLs, and it probably will work okay (it is still not advised that you do that
as that is an ODR violation).
However, one of the most likely candidate for `EC` -- `std::error_code` -- **does** depend
on the addresses of globals for correct functioning.
The standard library is required to implement globally unique addresses for the standard library
provided {{% api "std::error_category" %}} implementations e.g. `std::system_category()`.
User defined error code categories may **not** have unique global addresses, and thus
introduce misoperation.
`boost::system::error_code`, since version 1.69 does offer an *opt-in* guarantee
that it does not depend on the addresses of globals **if** the user defined error code
category *opts-in* to the 64-bit comparison mechanism. This can be seen in the specification of
`error_category::operator==` in
[Boost.System synopsis](https://www.boost.org/doc/libs/1_69_0/libs/system/doc/html/system.html#ref_synopsis).
Alternatively, the `status_code` in [Experimental Outcome](({{< relref "/experimental/differences" >}})),
due to its more modern design, does not suffer from any problems from being used in shared
libraries in any configuration.
## Why two types `result<>` and `outcome<>`, rather than just one?
`result` is the simple, success OR failure type.
`outcome` extends `result` with a third state to transport, conventionally (but not necessarily) some sort of "abort" or "exceptional" state which a function can return to indicate that not only did the operation fail, but it did so *catastrophically* i.e. please abort any attempt to retry the operation.
A perfect alternative to using `outcome` is to throw a C++ exception for the abort code path, and indeed most programs ought to do exactly that instead of using `outcome`. However there are a number of use cases where choosing `outcome` shines:
1. Where C++ exceptions or RTTI is not available, but the ability to fail catastrophically without terminating the program is important.
2. Where deterministic behaviour is required even in the catastrophic failure situation.
3. In unit test suites of code using Outcome it is extremely convenient to accumulate test failures into an `outcome` for later reporting. A similar convenience applies to RPC situations, where C++ exception throws need to be accumulated for reporting back to the initiating endpoint.
4. Where a function is "dual use deterministic" i.e. it can be used deterministically, in which case one switches control flow based on `.error()`, or it can be used non-deterministically by throwing an exception perhaps carrying a custom payload.
## How badly will including Outcome in my public interface affect compile times?
The quick answer is that it depends on how much convenience you want.
The convenience header `<result.hpp>` is dependent on `<system_error>` or Boost.System, which unfortunately includes `<string>` and thus
drags in quite a lot of other slow-to-parse stuff. If your public interface already includes `<string>`,
then the impact of additionally including Outcome will be low. If you do not include `<string>`,
unfortunately impact may be relatively quite high, depending on the total impact of your
public interface files.
If you've been extremely careful to avoid ever including the most of the STL headers
into your interfaces in order to maximise build performance, then `<basic_result.hpp>`
can have as few dependencies as:
1. `<cstdint>`
2. `<initializer_list>`
3. `<iosfwd>`
4. `<new>`
5. `<type_traits>`
6. `<cstdio>`
7. `<cstdlib>`
8. `<cassert>`
These, apart from `<iosfwd>`, tend to be very low build time impact in most standard
library implementations. If you include only `<basic_result.hpp>`, and manually configure
`basic_result<>` by hand, compile time impact will be minimised.
(See reference documentation for {{% api "basic_result<T, E, NoValuePolicy>" %}} for more detail.
## Is Outcome suitable for fixed latency/predictable execution coding such as for high frequency trading or audio?
Great care has been taken to ensure that Outcome never unexpectedly executes anything
with unbounded execution times such as `malloc()`, `dynamic_cast<>()` or `throw`.
Outcome works perfectly with C++ exceptions and RTTI globally disabled.
Outcome's entire design premise is that its users are happy to exchange a small, predictable constant overhead
during successful code paths, in exchange for predictable failure code paths.
In contrast, table-based exception handling gives zero run time overhead for the
successful code path, and completely unpredictable (and very expensive) overhead
for failure code paths.
For code where predictability of execution, no matter the code path, is paramount,
writing all your code to use Outcome is not a bad place to start. Obviously enough,
do choose a non-throwing policy when configuring `outcome` or `result` such as
{{% api "all_narrow" %}} to guarantee that exceptions can never be thrown by Outcome
(or use the convenience typedef for `result`, {{% api "unchecked<T, E = varies>" %}} which uses `policy::all_narrow`).
## What kind of runtime performance impact will using Outcome in my code introduce?
It is very hard to say anything definitive about performance impacts in codebases one
has never seen. Each codebase is unique. However to come up with some form of measure,
we timed traversing ten stack frames via each of the main mechanisms, including the
"do nothing" (null) case.
A stack frame is defined to be something called by the compiler whilst
unwinding the stack between the point of return in the ultimate callee and the base
caller, so for example ten stack allocated objects might be destructed, or ten levels
of stack depth might be unwound. This is not a particularly realistic test, but it
should at least give one an idea of the performance impact of returning Outcome's
`result` or `outcome` over say returning a plain integer, or throwing an exception.
The following figures are for Outcome v2.1.0 with GCC 7.4, clang 8.0 and Visual
Studio 2017.9. Figures for newer Outcomes with newer compilers can be found at
https://github.com/ned14/outcome/tree/develop/benchmark.
### High end CPU: Intel Skylake x64
This is a high end CPU with very significant ability to cache, predict, parallelise
and execute out-of-order such that tight, repeated loops perform very well. It has
a large μop cache able to wholly contain the test loop, meaning that these results
are a **best case** performance.
{{% figure src="/faq/results_skylake_log.png" title="Log graph comparing GCC 7.4, clang 8.0 and Visual Studio 2017.9 on x64, for exceptions-globally-disabled, ordinary and link-time-optimised build configurations." %}}
As you can see, throwing and catching an exception is
expensive on table-based exception handling implementations such as these, anywhere
between 26,000 and 43,000 CPU cycles. And this is the *hot path* situation, this
benchmark is a loop around hot cached code. If the tables are paged out onto storage,
you are talking about **millions** of CPU cycles.
Simple integer returns (i.e. do nothing null case)
are always going to be the fastest as they do the least work, and that costs 80 to 90
CPU cycles on this Intel Skylake CPU.
Note that returning a `result<int, std::error_code>` with a "success (error code)"
is no more than 5% added runtime overhead over returning a naked int on GCC and clang. On MSVC
it costs an extra 20% or so, mainly due to poor code optimisation in the VS2017.9 compiler. Note that "success
(experimental status code)" optimises much better, and has almost no overhead over a
naked int.
Returning a `result<int, std::error_code>` with a "failure (error code)"
is less than 5% runtime overhead over returning a success on GCC, clang and MSVC.
You might wonder what happens if type `E` has a non-trivial destructor, thus making the
`result<T, E>` have a non-trivial destructor? We tested `E = std::exception_ptr` and
found less than a 5% overhead to `E = std::error_code` for returning success. Returning a failure
was obviously much slower at anywhere between 300 and 1,100 CPU cycles, due to the
dynamic memory allocation and free of the exception ptr, plus at least two atomic operations per stack frame, but that is
still two orders of magnitude better than throwing and catching an exception.
We conclude that if failure is anything but extremely rare in your C++ codebase,
using Outcome instead of throwing and catching exceptions ought to be quicker overall:
- Experimental Outcome is statistically indistinguishable from the null case on this
high end CPU, for both returning success and failure, on all compilers.
- Standard Outcome is less than 5%
worse than the null case for returning successes on GCC and clang, and less than 10% worse than
the null case for returning failures on GCC and clang.
- Standard Outcome optimises
poorly on VS2017.9, indeed markedly worse than on previous point releases, so let's
hope that Microsoft fix that soon. It currently has a less than 20% overhead on the null case.
### Mid tier CPU: ARM Cortex A72
This is a four year old mid tier CPU used in many high end mobile phones and tablets
of its day, with good ability to cache, predict, parallelise
and execute out-of-order such that tight, repeated loops perform very well. It has
a μop cache able to wholly contain the test loop, meaning that these results
are a **best case** performance.
{{% figure src="/faq/results_arm_a72_log.png" title="Log graph comparing GCC 7.3 and clang 7.3 on ARM64, for exceptions-globally-disabled, ordinary and link-time-optimised build configurations." %}}
This ARM chip is a very consistent performer -- null case, success, or failure, all take
almost exactly the same CPU cycles. Choosing Outcome, in any configuration, makes no
difference to not using Outcome at all. Throwing and catching a C++ exception costs
about 90,000 CPU cycles, whereas the null case/Outcome costs about 130 - 140 CPU cycles.
There is very little to say about this CPU, other than Outcome is zero overhead on it. The same
applied to the ARM Cortex A15 incidentally, which I test cased extensively when
deciding on the Outcome v2 design back after the first peer review. The v2 design
was chosen partially because of such consistent performance on ARM.
### Low end CPUs: Intel Silvermont x64 and ARM Cortex A53
These are low end CPUs with a mostly or wholly in-order execution core. They have a small
or no μop cache, meaning that the CPU must always decode the instruction stream.
These results represent an execution environment more typical of CPUs two decades
ago, back when table-based EH created a big performance win if you never threw
an exception.
{{% figure src="/faq/results_silvermont_log.png" title="Log graph comparing GCC 7.3 and clang 7.3 on x64, for exceptions-globally-disabled, ordinary and link-time-optimised build configurations." %}}
{{% figure src="/faq/results_arm_a53_log.png" title="Log graph comparing GCC 7.3 and clang 7.3 on ARM64, for exceptions-globally-disabled, ordinary and link-time-optimised build configurations." %}}
The first thing to mention is that clang generates very high performance code for
in-order cores, far better than GCC. It is said that this is due to a very large investment by
Apple in clang/LLVM for their devices sustained over many years. In any case, if you're
targeting in-order CPUs, don't use GCC if you can use clang instead!
For the null case, Silvermont and Cortex A53 are quite similar in terms of CPU clock cycles. Ditto
for throwing and catching a C++ exception (approx 150,000 CPU cycles). However the Cortex
A53 does far better with Outcome than Silvermont, a 15% versus 100% overhead for Standard
Outcome, and a 4% versus 20% overhead for Experimental Outcome.
Much of this large difference is in fact due to calling convention differences. x64 permits up to 8 bytes
to be returned from functions by CPU register. `result<int>` consumes 24 bytes, so on x64
the compiler writes the return value to the stack. However ARM64 permits up to 64 bytes
to be returned in registers, so `result<int>` is returned via CPU registers on ARM64.
On higher end CPUs, memory is read and written in cache lines (32 or 64 bytes), and
reads and writes are coalesced and batched together by the out-of-order execution core. On these
low end CPUs, memory is read and written sequentially per assembler instruction,
so only one load or one store to L1
cache can occur at a time. This makes writing the stack particularly slow on in-order
CPUs. Memory operations which "disappear" on higher end CPUs take considerable time
on low end CPUs. This particularly punishes Silvermont in a way which does not punish
the Cortex A53, because of having to write multiple values to the stack to create the
24 byte object to be returned.
The conclusion to take away from this is that if you are targeting a low end CPU,
table-based EH still delivers significant performance improvements for the success
code path. Unless determinism in failure is critically important, you should not
use Outcome on in-order execution CPUs.
## Why is implicit default construction disabled?
This was one of the more interesting points of discussion during the peer review of
Outcome v1. v1 had a formal empty state. This came with many advantages, but it
was not felt to be STL idiomatic as `std::optional<result<T>>` is what was meant, so
v2 has eliminated any legal possibility of being empty.
The `expected<T, E>` proposal of that time (May 2017) did permit default construction
if its `T` type allowed default construction. This was specifically done to make
`expected<T, E>` more useful in STL containers as one can say resize a vector without
having to supply an `expected<T, E>` instance to fill the new items with. However
there was some unease with that design choice, because it may cause programmers to
use some type `T` whose default constructed state is overloaded with additional meaning,
typically "to be filled" i.e. a de facto empty state via choosing a magic value.
For the v2 redesign, the various arguments during the v1 review were considered.
Unlike `expected<T, E>` which is intended to be a general purpose Either monad
vocabulary type, Outcome's types are meant primarily for returning success or failure
from functions. The API should therefore encourage the programmer to not overload
the successful type with additional meaning of "to be filled" e.g. `result<std::optional<T>>`.
The decision was therefore taken to disable *implicit* default construction, but
still permit *explicit* default construction by making the programmer spell out their
intention with extra typing.
To therefore explicitly default construct a `result<T>` or `outcome<T>`, use one
of these forms as is the most appropriate for the use case:
1. Construct with just `in_place_type<T>` e.g. `result<T>(in_place_type<T>)`.
2. Construct via `success()` e.g. `outcome<T>(success())`.
3. Construct from a `void` form e.g. `result<T>(result<void>(in_place_type<void>))`.
## How far away from the proposed `std::expected<T, E>` is Outcome's `checked<T, E>`?
Not far, in fact after the first Boost.Outcome peer review in May 2017, Expected moved
much closer to Outcome, and Outcome deliberately provides {{% api "checked<T, E = varies>" %}}
as a semantic equivalent.
Here are the remaining differences which represent the
divergence of consensus opinion between the Boost peer review and WG21 on the proper
design for this object:
1. `checked<T, E>` has no default constructor. Expected has a default constructor if
`T` has a default constructor.
2. `checked<T, E>` uses the same constructor design as `std::variant<...>`. Expected
uses the constructor design of `std::optional<T>`.
3. `checked<T, E>` cannot be modified after construction except by assignment.
Expected provides an `.emplace()` modifier.
4. `checked<T, E>` permits implicit construction from both `T` and `E` when
unambiguous. Expected permits implicit construction from `T` alone.
5. `checked<T, E>` does not permit `T` and `E` to be the same, and becomes annoying
to use if they are constructible into one another (implicit construction self-disables).
Expected permits `T` and `E` to be the same.
6. `checked<T, E>` throws `bad_result_access_with<E>` instead of Expected's
`bad_expected_access<E>`.
7. `checked<T, E>` models `std::variant<...>`. Expected models `std::optional<T>`. Thus:
- `checked<T, E>` does not provide `operator*()` nor `operator->`
- `checked<T, E>` `.error()` is wide (i.e. throws on no-value) like `.value()`.
Expected's `.error()` is narrow (UB on no-error). [`checked<T, E>` provides
`.assume_value()` and `.assume_error()` for narrow (UB causing) observers].
8. `checked<T, E>` uses `success<T>` and `failure<E>` type sugars for disambiguation.
Expected uses `unexpected<E>` only.
9. `checked<T, E>` does not implement (prone to unintended misoperation) comparison
operators which permit implicit conversion e.g. `checked<T> == T` will fail to compile.
Instead write unambiguous code e.g. `checked<T> == success(T)` or `checked<T> == failure(T)`.
10. `checked<T, E>` defaults `E` to `std::error_code` or `boost::system::error_code`.
Expected does not default `E`.
In fact, the two are sufficiently close in design that a highly conforming `expected<T, E>`
can be implemented by wrapping up `checked<T, E>` with the differing functionality:
{{% snippet "expected_implementation.cpp" "expected_implementation" %}}
## Why doesn't Outcome duplicate `std::expected<T, E>`'s design?
There are a number of reasons:
1. Outcome is not aimed at the same audience as Expected. We target developers
and users who would be happy to use Boost. Expected targets the standard library user.
2. Outcome believes that the monadic use case isn't as important as Expected does.
Specifically, we think that 99% of use of Expected in the real world will be to
return failure from functions, and not as some sort of enhanced or "rich" Optional.
Outcome therefore models a subset of Variant, whereas Expected models an extended Optional.
3. Outcome believes that if you are thinking about using something like Outcome,
then for you writing failure code will be in the same proportion as writing success code,
and thus in Outcome writing for failure is exactly the same as writing for success.
Expected assumes that success will be more common than failure, and makes you type
more when writing for failure.
4. Outcome goes to considerable effort to help the end user type fewer characters
during use. This results in tighter, less verbose, more succinct code. The cost of this is a steeper
learning curve and more complex mental model than when programming with Expected.
5. Outcome has facilities to make easier interoperation between multiple third
party libraries each using incommensurate Outcome (or Expected) configurations. Expected does
not do any of this, but subsequent WG21 papers do propose various interoperation
mechanisms, [one of which](https://wg21.link/P0786) Outcome implements so code using Expected will seamlessly
interoperate with code using Outcome.
6. Outcome was designed with the benefit of hindsight after Optional and Expected,
where how those do implicit conversions have been found to be prone to writing
unintentionally buggy code. Outcome simultaneously permits more implicit conversions
for ease of use and convenience, where those are unambigiously safe, and prevents
other implicit conversions which the Boost peer review reported as dangerous.
## Is Outcome riddled with undefined behaviour for const, const-containing and reference-containing types?
The short answer is not any more in C++ 20 and after, thanks to changes made to
C++ 20 at the Belfast WG21 meeting in November 2019.
The longer answer is that before C++ 20, use of placement
new on types containing `const` member types where the resulting pointer was
thrown away is undefined behaviour. As of the resolution of a national body
comment, this is no longer the case, and now Outcome is free of this particular
UB for C++ 20 onwards.
This still affects C++ before 20, though no major compiler is affected. Still,
if you wish to avoid UB, don't use `const` types within Outcome types (or any
`optional<T>`, or `vector<T>` or any STL container type for that matter).
### More detail
Before the C++ 14 standard, placement new into storage which used to contain
a const type was straight out always undefined behaviour, period. Thus all use of
placement new within a `result<const_containing_type>`, or indeed an `optional<const_containing_type>`, is always
undefined behaviour before C++ 14. From `[basic.life]` for the C++ 11 standard:
> Creating a new object at the storage location that a const object with static,
> thread, or automatic storage duration occupies or, at the storage location
> that such a const object used to occupy before its lifetime ended results
> in undefined behavior.
This being excessively restrictive, from C++ 14 onwards, `[basic_life]` now states:
> If, after the lifetime of an object has ended and before the storage which
> the object occupied is reused or released, a new object is created at the
> storage location which the original object occupied, a pointer that
> pointed to the original object, a reference that referred to the original
> object, or the name of the original object will automatically refer to the
> new object and, once the lifetime of the new object has started, can be
> used to manipulate the new object, if:
>
> — the storage for the new object exactly overlays the storage location which
> the original object occupied, and
>
> — the new object is of the same type as the original object (ignoring the
> top-level cv-qualifiers), and
>
> — the type of the original object is not const-qualified, and, if a class type,
> does not contain any non-static data member whose type is const-qualified
> or a reference type, and
>
> — neither the original object nor the new object is a potentially-overlapping
> subobject
Leaving aside my personal objections to giving placement new of non-const
non-reference types magical pointer renaming powers, the upshot is that if
you want defined behaviour for placement new of types containing const types
or references, you must store the pointer returned by placement new, and use
that pointer for all further reference to the newly created object. This
obviously adds eight bytes of storage to a `result<const_containing_type>`, which is highly
undesirable given all the care and attention paid to keeping it small. The alternative
is to use {{% api "std::launder" %}}, which was added in C++ 17, to 'launder'
the storage into which we placement new before each and every use of that
storage. This forces the compiler to reload the object stored by placement
new on every occasion, and not assume it can be constant propagated, which
impacts codegen quality.
As mentioned above, this issue (in so far as it applies to types containing
user supplied `T` which might be `const`) has been resolved as of C++ 20 onwards,
and it is extremely unlikely that any C++ compiler will act on any UB here in
C++ 17 or 14 given how much of STL containers would break.
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/recipes/asio-integration.md | +++
title = "ASIO/Networking TS : Boost < 1.70"
description = "How to teach ASIO/Networking TS about Outcome."
tags = [ "asio", "networking-ts" ]
+++
*Thanks to [Christos Stratopoulos](https://github.com/cstratopoulos) for this Outcome recipe.*
---
### Compatibility note
This recipe targets Boost versions before 1.70, where coroutine support is based around
the `asio::experimental::this_coro::token` completion token. For integration with Boost
versions 1.70 and onward, see [this recipe](asio-integration-1-70).
---
### Use case
[Boost.ASIO](https://www.boost.org/doc/libs/develop/doc/html/boost_asio.html)
and [standalone ASIO](https://think-async.com/Asio/) provide the
[`async_result`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/async_result.html)
customisation point for adapting arbitrary third party libraries, such as Outcome, into ASIO.
Historically in ASIO you need to pass completion handler instances
to the ASIO asynchronous i/o initiation functions. These get executed when the i/o
completes.
{{% snippet "boost-only/asio_integration.cpp" "old-use-case" %}}
One of the big value adds of the Coroutines TS is the ability to not have to write
so much boilerplate if you have a Coroutines supporting compiler:
{{% snippet "boost-only/asio_integration.cpp" "new-use-case" %}}
The default ASIO implementation always throws exceptions on failure through
its coroutine token transformation. The [`redirect_error`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/experimental__redirect_error.html)
token transformation recovers the option to use the `error_code` interface,
but it suffers from the [same drawbacks]({{< relref "/motivation/error_codes" >}})
that make pure error codes unappealing in the synchronous case.
This recipe fixes that by making it possible for coroutinised
i/o in ASIO to return a `result<T>`:
{{% snippet "boost-only/asio_integration.cpp" "outcome-use-case" %}}
---
### Implementation
{{% notice warning %}}
The below involves a lot of ASIO voodoo. **NO SUPPORT WILL BE GIVEN HERE FOR THE ASIO
CODE BELOW**. Please raise any questions or problems that you have with how to implement
this sort of stuff in ASIO
on [Stackoverflow #boost-asio](https://stackoverflow.com/questions/tagged/boost-asio).
{{% /notice %}}
The real world, production-level recipe can be found at the bottom of this page.
You ought to use that in any real world use case.
It is however worth providing a walkthrough of a simplified edition of the real world
recipe, as a lot of barely documented ASIO voodoo is involved. You should not
use the code presented next in your own code, it is too simplified. But it should
help you understand how the real implementation works.
Firstly we need to define some helper type sugar and a factory function for wrapping
any arbitrary third party completion token with that type sugar:
{{% snippet "boost-only/asio_integration.cpp" "as_result" %}}
Next we tell ASIO about a new completion token it ought to recognise by specialising
[`async_result`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/async_result.html):
{{% snippet "boost-only/asio_integration.cpp" "async_result1" %}}
The tricky part to understand is that our `async_result` specialisation inherits
from an `async_result` for the supplied completion token type with a completion
handler which consumes a `result<T>`. Our `async_result` is actually therefore
the base `async_result`, but we layer on top a `completion_handler_type` with
the `void(error_code, size_t)` signature which constructs from that a `result`:
{{% snippet "boost-only/asio_integration.cpp" "async_result2" %}}
To use, simply wrap the third party completion token with `as_result` to cause
ASIO to return from `co_await` a `result` instead of throwing exceptions on
failure:
```c++
char buffer[1024];
asio::experimental::await_token token =
co_await asio::experimental::this_coro::token();
outcome::result<size_t, error_code> bytesread =
co_await skt.async_read_some(asio::buffer(buffer), as_result(token));
```
The real world production-level implementation below is a lot more complex than the
above which has been deliberately simplified to aid exposition. The above
should help you get up and running with the below, eventually.
One again I would like to remind you that Outcome is not the appropriate place
to seek help with ASIO voodoo. Please ask on
[Stackoverflow #boost-asio](https://stackoverflow.com/questions/tagged/boost-asio).
---
Here follows the real world, production-level adapation of Outcome into
ASIO, written and maintained by [Christos Stratopoulos](https://github.com/cstratopoulos).
If the following does not load due to Javascript being disabled, you can visit the gist at
https://gist.github.com/cstratopoulos/901b5cdd41d07c6ce6d83798b09ecf9b/da584844f58353915dc2600fba959813f793b456.
{{% gist "cstratopoulos" "901b5cdd41d07c6ce6d83798b09ecf9b/da584844f58353915dc2600fba959813f793b456" %}}
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/recipes/_index.md | +++
title = "Recipes"
weight = 12
+++
{{% children description="true" depth="2" %}}
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/recipes/asio-integration-1-70.md | +++
title = "ASIO/Networking TS: Boost >= 1.70"
description = "How to teach ASIO/Networking TS about Outcome."
tags = [ "asio", "networking-ts" ]
+++
*Thanks to [Christos Stratopoulos](https://github.com/cstratopoulos) for this Outcome recipe.*
---
### Compatibility note
This recipe targets Boost versions including and after 1.70, where coroutine support is
based around the `asio::use_awaitable` completion token. For integration with Boost versions
before 1.70, see [this recipe](asio-integration).
---
### Use case
[Boost.ASIO](https://www.boost.org/doc/libs/develop/doc/html/boost_asio.html)
and [standalone ASIO](https://think-async.com/Asio/) provide the
[`async_result`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/async_result.html)
customisation point for adapting arbitrary third party libraries, such as Outcome, into ASIO.
Historically in ASIO you need to pass completion handler instances
to the ASIO asynchronous i/o initiation functions. These get executed when the i/o
completes.
{{% snippet "boost-only/asio_integration_1_70.cpp" "old-use-case" %}}
One of the big value adds of the Coroutines TS is the ability to not have to write
so much boilerplate if you have a Coroutines supporting compiler:
{{% snippet "boost-only/asio_integration_1_70.cpp" "new-use-case" %}}
The default ASIO implementation always throws exceptions on failure through
its coroutine token transformation. The [`redirect_error`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/experimental__redirect_error.html)
token transformation recovers the option to use the `error_code` interface,
but it suffers from the [same drawbacks]({{< relref "/motivation/error_codes" >}})
that make pure error codes unappealing in the synchronous case.
This recipe fixes that by making it possible for coroutinised
i/o in ASIO to return a `result<T>`:
{{% snippet "boost-only/asio_integration_1_70.cpp" "outcome-use-case" %}}
---
### Implementation
{{% notice warning %}}
The below involves a lot of ASIO voodoo. **NO SUPPORT WILL BE GIVEN HERE FOR THE ASIO
CODE BELOW**. Please raise any questions or problems that you have with how to implement
this sort of stuff in ASIO
on [Stackoverflow #boost-asio](https://stackoverflow.com/questions/tagged/boost-asio).
{{% /notice %}}
The real world, production-level recipe can be found at the bottom of this page.
You ought to use that in any real world use case.
It is however worth providing a walkthrough of a simplified edition of the real world
recipe, as a lot of barely documented ASIO voodoo is involved. You should not
use the code presented next in your own code, it is too simplified. But it should
help you understand how the real implementation works.
Firstly we need to define some helper type sugar and a factory function for wrapping
any arbitrary third party completion token with that type sugar:
{{% snippet "boost-only/asio_integration_1_70.cpp" "as_result" %}}
Next we tell ASIO about a new completion token it ought to recognise by specialising
[`async_result`](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/async_result.html):
{{% snippet "boost-only/asio_integration_1_70.cpp" "async_result1" %}}
There are a couple tricky parts to understand. First of all, we want our
`async_result` specialization to work, in particular, with the `async_result` for
ASIO's
[`use_awaitable_t` completion token](https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/use_awaitable_t.html).
With this token, the `async_result` specialization takes the form with a static
`initiate` method which defers initiation of the asynchronous operation until,
for example,
`co_await` is called on the returned `awaitable`. Thus, our `async_result`
specialization will take the same form. With this in mind, we need only
understand how our specialization will implement its `initiate` method. The trick
is that it will pass the initiation work off to an `async_result` for the
supplied completion token type with a completion handler which consumes `result<T>`.
Our `async_result` is thus just a simple wrapper over this underlying
`async_result`, but we inject a completion handler with the
`void(error_code, size_t)` signature which constructs from that a `result`:
{{% snippet "boost-only/asio_integration_1_70.cpp" "async_result2" %}}
To use, simply wrap the third party completion token with `as_result` to cause
ASIO to return from `co_await` a `result` instead of throwing exceptions on
failure:
```c++
char buffer[1024];
outcome::result<size_t, error_code> bytesread =
co_await skt.async_read_some(asio::buffer(buffer), as_result(asio::use_awaitable));
```
The real world production-level implementation below is a lot more complex than the
above which has been deliberately simplified to aid exposition. The above
should help you get up and running with the below, eventually.
One again I would like to remind you that Outcome is not the appropriate place
to seek help with ASIO voodoo. Please ask on
[Stackoverflow #boost-asio](https://stackoverflow.com/questions/tagged/boost-asio).
---
Here follows the real world, production-level adapation of Outcome into
ASIO, written and maintained by [Christos Stratopoulos](https://github.com/cstratopoulos).
If the following does not load due to Javascript being disabled, you can visit the gist at
https://gist.github.com/cstratopoulos/901b5cdd41d07c6ce6d83798b09ecf9b/863c1dbf3b063a5ff9ff2bdd834242ead556e74e.
{{% gist "cstratopoulos" "901b5cdd41d07c6ce6d83798b09ecf9b/863c1dbf3b063a5ff9ff2bdd834242ead556e74e" %}}
|
0 | repos/outcome/doc/src/content | repos/outcome/doc/src/content/recipes/foreign-try.md | +++
title = "Extending `OUTCOME_TRY`"
description = "How to informing `OUTCOME_TRY` about foreign Result types."
tags = [ "TRY" ]
+++
Outcome's {{% api "OUTCOME_TRY(var, expr)" %}} operation is fully extensible
to accept as input any foreign types.
It already recognises types matching the
{{% api "concepts::value_or_error<T, E>" %}} concept, which is to say all types which have:
- A public `.has_value()` member function which returns a `bool`.
- In order of preference, a public `.assume_value()`/`.value()` member
function.
- In order of preference, a public `.as_failure()`/`.assume_error()`/`.error()`
member function.
This should automatically handle inputs of `std::expected<T, E>`, and many others,
including intermixing Boost.Outcome and standalone Outcome within the same
translation unit.
`OUTCOME_TRY` has the following free function customisation points:
<dl>
<dt><code>OUTCOME_V2_NAMESPACE::</code>{{% api "try_operation_has_value(X)" %}}
<dd>Returns a `bool` which is true if the input to TRY has a value.
<dt><code>OUTCOME_V2_NAMESPACE::</code>{{% api "try_operation_return_as(X)" %}}
<dd>Returns a suitable {{% api "failure_type<EC, EP = void>" %}} which
is returned immediately to cause stack unwind. Ought to preserve rvalue
semantics (i.e. if passed an rvalue, move the error state into the failure
type).
<dt><code>OUTCOME_V2_NAMESPACE::</code>{{% api "try_operation_extract_value(X)" %}}
<dd>Extracts a value type from the input for the `TRY` to set its variable.
Ought to preserve rvalue semantics (i.e. if passed an rvalue, move the value).
</dl>
New overloads of these to support additional input types must be injected into
the `OUTCOME_V2_NAMESPACE` namespace before the compiler parses the relevant
`OUTCOME_TRY` in order to be found. This is called 'early binding' in the two
phase name lookup model in C++. This was chosen over 'late binding', where an
`OUTCOME_TRY` in a templated piece of code could look up overloads introduced after
parsing the template containing the `OUTCOME_TRY`, because it has much lower
impact on build times, as binding is done once at the point of parse, instead
of on every occasion at the point of instantiation. If you are careful to ensure
that you inject the overloads which you need early in the parse of the
translation unit, all will be well.
Let us work through an applied example.
---
## A very foreign pseudo-Expected type
This is a paraphrase of a poorly written pseudo-Expected type which I once
encountered in the production codebase of a large multinational. Lots
of the code was already using it, and it was weird enough that it couldn't
be swapped out for something better easily.
{{% snippet "foreign_try.cpp" "foreign_type" %}}
What we would like is for new code to be written using Outcome, but be able
to transparently call old code, like this:
{{% snippet "foreign_try.cpp" "functions" %}}
Telling Outcome about this weird foreign Expected is straightforward:
{{% snippet "foreign_try.cpp" "tell_outcome" %}}
And now `OUTCOME_TRY` works exactly as expected:
{{% snippet "foreign_try.cpp" "example" %}}
... which outputs:
```
new_code(5) returns successful 5
new_code(0) returns failure argument out of domain
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.