Is it possible to determine the number of elements of a c++ enum class?

后端 未结 13 1816
长情又很酷
长情又很酷 2020-12-13 01:39

Is it possible to determine the cardinality of a c++ enum class:

enum class Example { A, B, C, D, E };

I tried to use si

13条回答
  •  悲哀的现实
    2020-12-13 02:00

    Another kind of "stupid" solution to this is:

    enum class Example { A, B, C, D, E };
    
    constexpr int ExampleCount = [] {
      Example e{};
      int count = 0;
      switch (e) {
        case Example::A:
          count++;
        case Example::B:
          count++;
        case Example::C:
          count++;
        case Example::D:
          count++;
        case Example::E:
          count++;
      }
    
      return count;
    }();
    

    By compiling this with -Werror=switch you make sure to get a compiler warning if you omit or duplicate any switch case. It's also constexpr so this is computed at compile time.

    But note that even for a en enum class the default initialized value is 0 even if the first value of the enum is not 0. So you have to either start on 0 or explicitly use the first value.

提交回复
热议问题