How to check if enum value is valid?

前端 未结 8 1276
一向
一向 2020-11-27 06:38

I am reading an enum value from a binary file and would like to check if the value is really part of the enum values. How can I do it?



        
相关标签:
8条回答
  • 2020-11-27 07:26

    Managed Extensions for C++ supports the following syntax:

    enum Abc
    {
        A = 4,
        B = 8,
        C = 12
    };
    
    Enum::IsDefined(Abc::typeid, 8);
    

    Reference: MSDN "Managed Extensions for C++ Programming"

    0 讨论(0)
  • 2020-11-27 07:35

    enum value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }, the value of 2 is considered a valid enum value.

    Consider 7.2/6 of standard:

    For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators.

    There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.

    See Similar Question about how to cast int to enum for further details.

    0 讨论(0)
提交回复
热议问题