Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Prev Up HomeNext

Implicit construction

The preceding code had the compiler stamp out a custom status code domain for a user supplied enum. You now get the following types:

// This is the status code generated for your custom enum type. It will implicitly construct from
// values of enum custom_failure.
using custom_failure_code = BOOST_OUTCOME_SYSTEM_ERROR2_NAMESPACE::quick_status_code_from_enum_code<custom_failure>;

namespace outcome_e = BOOST_OUTCOME_V2_NAMESPACE::experimental;

// You don't usually need to use the status code type explicitly, because this "just works":
outcome_e::status_result<int> positive_only(int x)
{
  if(x < 0)
  {
    // Outcome's result sees that status_code will implicitly construct from this enum,
    // and it returns an errored result
    return custom_failure::bad_argument;
  }
  return x;
}

// Semantic comparisons work
bool test(int x)
{
  if(auto r = positive_only(x); !r)
  {
    if(r.error() == outcome_e::errc::invalid_argument)
    {
      std::cerr << "Positive numbers only!" << std::endl;
      return false;
    }
  }
  return true;
}
View this code on Github

As you can see, this is less work than plugging your custom enum into std::error_code. It also has C compatibility, and generates better codegen.

Last revised: July 16, 2024 at 21:33:35 +0100


Prev Up HomeNext