std::expected(3)
π NAME π
std::expected β std::expected, literally the main character of this page π
. Bestie, this is the std::expected(3) manpage and itβs about to eat.
πΈ Synopsis πΈ
Defined in header <expected>.
template< class T, class E > (since C++23)
class expected;
The class template std::expected gives you a way to store either of two values. An object of std::expected at any given time either holds an expected value of type T, or an unexpected value of type E. std::expected is never valueless β no cap, it always has something in it β¨.
The stored value is allocated directly within the storage occupied by the expected object. No dynamic memory allocation takes place. Periodt.
A program is ill-formed if it instantiates anexpectedwith a reference type, a function type, or a specialization ofstd::unexpected. In addition,Tmust not bestd::in_place_torstd::unexpect_t. Thatβs the rule, bestie π.
π§ Template parameters π§
Tβ the type of the expected value. The type must either be (possibly cv-qualified)void, or meet theDestructiblerequirements (in particular, array and reference types are not allowed, so donβt even try it π).Eβ the type of the unexpected value. The type must meet theDestructiblerequirements, and must be a valid template argument forstd::unexpected(in particular, arrays, non-object types, and cv-qualified types are not allowed π«Ά).
π¦ Member types π¦
value_typeβTerror_typeβEunexpected_typeβstd::unexpected<E>
π Member alias templates π
rebind<U>βexpected<U, error_type>
π Member functions π
constructorβ constructs the expected object (public member function)destructorβ destroys the expected object, along with its contained value (public member function)operator=β assigns contents (public member function)
π Observers π
operator->,operator*β accesses the expected value (public member function)operator boolβ checks whether the object contains an expected value (public member function)has_valueβ checks whether the object contains an expected value (public member function)valueβ returns the expected value (public member function)errorβ returns the unexpected value (public member function)value_orβ returns the expected value if present, another value otherwise (public member function)
π Monadic operations π
and_thenβ returns the result of the given function on the expected value if it exists; otherwise, returns the expected itself (public member function)transformβ returns an expected containing the transformed expected value if it exists; otherwise, returns the expected itself (public member function)or_elseβ returns the expected itself if it contains an expected value; otherwise, returns the result of the given function on the unexpected value (public member function)transform_errorβ returns the expected itself if it contains an expected value; otherwise, returns an expected containing the transformed unexpected value (public member function)
π Modifiers π
emplaceβ constructs the expected value in-place (public member function)swapβ exchanges the contents (public member function)
π₯ Non-member functions π₯
operator==β compares expected objects (C++23) (function template)swap(std::expected)β specializes thestd::swapalgorithm (C++23) (function)
π§ Helper classes π§
unexpectedβ represented as an unexpected value (C++23) (class template)bad_expected_accessβ exception indicating checked access to an expected that contains an unexpected value (C++23) (class template)unexpectβ in-place construction tag for unexpected value in expectedunexpect_tβ (tag) (C++23)
π Notes π
Types with the same functionality are called Result in Rust and Either in Haskell. Cute crossover lore, honestly π«Ά.
π§ͺ Feature-test macro
__cpp_lib_expectedβ202202L(C++23): class templatestd::expectedand associated helper classes__cpp_lib_expectedβ202211L(C++23): Monadic functions forstd::expected
β¨ Example β¨
// Run this code
#include <cmath>
#include <expected>
#include <iomanip>
#include <iostream>
#include <string_view>
enum class parse_error
{
invalid_input,
overflow
};
auto parse_number(std::string_view& str) -> std::expected<double,
parse_error>
{
const char* begin = str.data();
char* end;
double retval = std::strtod(begin, &end);
if (begin == end)
return std::unexpected(parse_error::invalid_input);
else if (std::isinf(retval))
return std::unexpected(parse_error::overflow);
str.remove_prefix(end - begin);
return retval;
}
int main()
{
auto process = [](std::string_view str)
{
std::cout << "str: " << std::quoted(str) << ", ";
if (const auto num = parse_number(str); num.has_value())
std::cout << "value: " << *num << '\n';
// If num did not have a value, dereferencing num
// would cause an undefined behavior, and
// num.value() would throw std::bad_expected_access.
// num.value_or(123) uses specified default value 123.
else if (num.error() == parse_error::invalid_input)
std::cout << "error: invalid input\n";
else if (num.error() == parse_error::overflow)
std::cout << "error: overflow\n";
else
std::cout << "unexpected!\n"; // or invoke std::unreachable();
};
for (auto src : {"42", "42abc", "meow", "inf"})
process(src);
}
π€ Output
str: "42", value: 42
str: "42abc", value: 42
str: "meow", error: invalid input
str: "inf", error: overflow
π References π
- C++23 standard (ISO/IEC 14882:2023):
- 22.8 Expected objects [expected]
π See also π
variantβ a type-safe discriminated union (C++17) (class template)optionalβ a wrapper that may or may not hold an object (C++17) (class template)
Thatβs the wrap, bestie π«Ά β this page came fromhttp://cppreference.com, dated2024.06.10, and itβs thestd::expected(3)manpage. Mwah π.
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms