lib/expected.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <string>
#include <expected>

// convert string to int if possible or return error message:
std::expected<int, std::string> asInt(const std::string& s)
{
  try {
    return std::stoi(s);
  }
  catch (...) {
    return std::unexpected{"cannot convert \"" + s + "\" to int"};
  }
}

int main()
{  
  for (auto s : {"42", "  077", "hello", "0x33"} ) {
    // try to convert s to int and print the result if possible or errors message if not:
    std::expected exp = asInt(s);
    if (exp) {
      std::cout << "convert '" << s << "' to int: " << *exp << "\n";
    }
    else {
      std::cout << "ERROR: " << exp.error() << '\n';
    }
  }
}