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

后端 未结 13 1775
长情又很酷
长情又很酷 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:10

    constexpr auto TEST_START_LINE = __LINE__;
    enum class TEST { // Subtract extra lines from TEST_SIZE if an entry takes more than one 
        ONE = 7
      , TWO = 6
      , THREE = 9
    };
    constexpr auto TEST_SIZE = __LINE__ - TEST_START_LINE - 3;
    

    This is derived from UglyCoder's answer but improves it in three ways.

    • There are no extra elements in the type_safe enum (BEGIN and SIZE) (Cameron's answer also has this problem.)
      • The compiler will not complain about them being missing from a switch statement (a significant problem)
      • They cannot be passed inadvertently to functions expecting your enum. (not a common problem)
    • It does not require casting for use. (Cameron's answer has this problem too.)
    • The subtraction does not mess with the size of the enum class type.

    It retains UglyCoder's advantage over Cameron's answer that enumerators can be assigned arbitrary values.

    A problem (shared with UglyCoder but not with Cameron) is that it makes newlines and comments significant ... which is unexpected. So someone could add an entry with whitespace or a comment without adjusting TEST_SIZE's calculation.

提交回复
热议问题