dimanche 21 février 2021

static_cast to enum class from underlying type value and switch for compiler assistance

Suppose I have an enum:

enum class Thing : std::uint8_t {
  Foo = 21,
  Bar = 42,
  Baz = 1
};

I want to convert a "raw" value (of the underlying type) to a value of that enum, with error handling catching values which are not "a thing". I could use checks like if (raw_value == static_cast<std::uint8_t>(Thing::Foo)) and then an else with the error handling, but then I could forget for example Thing::Baz. However, when I switch over a value of type Thing, then my compiler (as probably most modern compilers) warns me about unhandled enumeration values ("enumeration value Baz not handled in switch").

So I came up with this:

Thing thingFromUInt8(std::uint8_t const b) {
  Thing const t = static_cast<Thing>(b);
  switch (t) {
    case Thing::Foo:
    case Thing::Bar:
    case Thing::Baz:
      return t;
  }
  throw std::runtime_error("That's not a thing...");
}

Questions:

  • Is this "legal" C++ (C++11 and above)?
  • If it is, does it have any drawbacks?

Aucun commentaire:

Enregistrer un commentaire