0Pricing
C++ Academy · Lesson

std::expected Basics

Return values or errors.

Values or Errors

std::expected<T, E> (C++23) holds either a successful value of type T or an error of type E. Unlike optional, it carries why it failed. Include <expected>.

Returning Success

On success you return the value directly; it is stored as the "expected" type T.

#include <expected>
#include <iostream>
std::expected<int, std::string> parse(bool ok) {
    if (ok) return 100;
    return std::unexpected("bad input");
}
int main() {
    auto r = parse(true);
    if (r) std::cout << *r << "\n";
}

All lessons in this course

  1. Representing Absence with optional
  2. Accessing optional Values
  3. std::expected Basics
  4. Error Handling Patterns
← Back to C++ Academy