How to check if an enum variable is valid?

前端 未结 7 1019
执笔经年
执笔经年 2021-01-11 11:07

I have an enum:

enum myenum{
  typeA,
  typeB,
  typeC
} myenum_t;

Then, a functions is to be called with an enum parameter:



        
7条回答
  •  生来不讨喜
    2021-01-11 11:53

    Enumerations in C++ already have stronger types than in C.

    Take the following simple program:

    #include 
    
    enum E
    {
        A,
        B 
    };
    
    void f(E e)
    {
    }
    
    int main()
    {
        f(1);
    }
    

    Using the GCC compiler I will get a this error:

    enum.cpp: In function ‘int main()’:
    enum.cpp:15: error: invalid conversion from ‘int’ to ‘E’
    enum.cpp:15: error:   initializing argument 1 of ‘void f(E)’
    

    So as you can see the enumeration members are already checked.

    If you want even stronger type checking, and have a C++11 capable compiler, you can use even stronger type checking for enums, see http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations.

提交回复
热议问题