How to check if enum value is valid?

前端 未结 8 1728
一向
一向 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:20

    Speaking about a language, there is no better way, the enum values exist compile time only and there is no way to enumerate them programatically. With a well thought infrastructure you may still be able to avoid listing all values several times, though. See Easy way to use variables of enum types as string in C?

    Your sample can then be rewritten using the "enumFactory.h" provided there as:

    #include "enumFactory.h"
    
    #define ABC_ENUM(XX) \
        XX(A,=4) \
        XX(B,=8) \
        XX(C,=12) \
    
    DECLARE_ENUM(Abc,ABC_ENUM)
    
    int main()
    {
        int v1 = 4;
        Abc v2 = static_cast< Abc >( v1 );
    
        #define CHECK_ENUM_CASE(name,assign) case name: std::cout<< #name <

    or even (using some more facilities already existing in that header):

    #include "enumFactory.h"
    
    #define ABC_ENUM(XX) \
        XX(A,=4) \
        XX(B,=8) \
        XX(C,=12) \
    
    DECLARE_ENUM(Abc,ABC_ENUM)
    DEFINE_ENUM(Abc,ABC_ENUM)
    
    int main()
    {
        int v1 = 4;
        Abc v2 = static_cast< Abc >( v1 );
        const char *name = GetString(v2);
        if (name[0]==0) name = "no match found";
        std::cout << name << std::endl;
    }
    

提交回复
热议问题