1

Given a scoped enum, is it possible to convert to the underlying type without explicitly specifying the underlying type?

Example:

enum class HeapCorruptionDetectMethod {//default is int
    write_on_freed,
    buffer_underrun,
    buffer_overrun
};

auto active_method = HeapCorruptionDetectMethod::write_on_freed;

//...

//agnostic about the underlying type:
auto index = static_cast<*underlying_type*>(active_method);

In other words, is it possible to query the underlying type?

NutCracker
  • 11,485
  • 4
  • 44
  • 68
darune
  • 10,480
  • 2
  • 24
  • 62
  • 6
    I’m somewhat amused, since this is *literally* the first Google hit for “[underlying_type](https://www.google.com/search?q=underlying_type)”. – Konrad Rudolph Feb 06 '20 at 10:38
  • sorry for picking on words, but `auto` and getting the underlying type without explicitly mentioning it I would not call "agnostic". The type is still there, you just dont have to mention it explicitly. `index` is of certain type and depending on how you use it, its type can make a difference – 463035818_is_not_an_ai Feb 06 '20 at 10:53

1 Answers1

1

You can try following template function which I find very handy and expressive:

template <typename Enum>
constexpr typename std::enable_if<std::is_enum<Enum>::value, typename std::underlying_type<Enum>::type>::type
get_underlying(Enum const& value) {
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

And then you can use it like this:

enum class Foo : int {
    A = 0,
    B = 1
};

int main() {
    std::cout << get_underlying(Foo::A) << std::endl; // 0
    std::cout << get_underlying(Foo::B) << std::endl; // 1

    return 0;
}

Check it out live

NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • 2
    what is the purpose of the function? Why not simply `static_cast::type>(Foo::A);` ? – 463035818_is_not_an_ai Feb 06 '20 at 10:50
  • @idclev463035818 just a handy function, more readable and generic. you don't like it? – NutCracker Feb 06 '20 at 10:51
  • frankly, no. I dont see the benefit of using it. Basically you just give a different name to something that already exists, this rather decreases readability. `static_cast` and `std::underlying_type` I know, with `get_underlying` I have to read the function to know what it does – 463035818_is_not_an_ai Feb 06 '20 at 10:59
  • @idclev463035818 hmm, i would say it increases readability (i.e. improves code expressiveness) by hiding things that are unnecessary to know – NutCracker Feb 06 '20 at 11:04
  • i have a clear opinion, but I didnt vote, because it is just an opinion. Readability is subjective, though consider that what you want to do is "cast to the underlying type", so neither `static_cast` nor `std::underlying_type` are unnecessary to know, rather they are the standard way to express exactly that – 463035818_is_not_an_ai Feb 06 '20 at 11:06