5

With the following code I can check at compile time if type E is an enum:

static_assert(true == std::is_enum<E>::value, "Must be an enum");

How can I check if it is an enum class?

Here they suggest to add the check !std::is_convertible<T, int>::value, but it looks like a trick. Is there a better way?

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 1
    My first idea would be an SFINAE test for something like "can you add integers to it" , but that can be fooled by a free `operator+`... – Max Langhof Aug 30 '19 at 13:59
  • 2
    There is no built-in function in the Standard Library. This [SO post](https://stackoverflow.com/questions/10724783/is-it-possible-to-determine-if-a-type-is-a-scoped-enumeration-type) seems to do the trick. – Ron Aug 30 '19 at 14:00
  • 1
    _"Is there a better way?"_: according to what criterion? As is, this question is opinion-based ;) – YSC Aug 30 '19 at 14:01
  • 6
    *"but it looks like a trick"* Everything about template metaprogramming is a trick. It's a C++ feature that was discovered, not designed. – François Andrieux Aug 30 '19 at 14:03
  • @YSC obviously that does not look like a trick – Slava Aug 30 '19 at 14:04
  • @Ron, your link answers my question. Thanks. – Pietro Aug 30 '19 at 14:04
  • 1
    Why do you care if it is an enum class? (If the reason involves avoiding an implicit conversion to `int`, then your "trick" might be more appropriate than something saying "is an enum class".) – JaMiT Aug 30 '19 at 14:04
  • @Slava I wager you're being sarcastic (and if you do: :D), but just to be sure (Poe's law after all) ... On what criterion does a solution looks more or less like a trick? :) – YSC Aug 30 '19 at 14:13
  • @YSC non tricky code should clearly show intentions. For example `std::is_enum` does, `std::doing_that_with_int and std::not_doing_this_with_char` does not. – Slava Aug 31 '19 at 15:30

0 Answers0