Using default in a switch statement when switching over an enum

后端 未结 16 1301
一个人的身影
一个人的身影 2020-12-15 02:57

What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you\'d like the code to be future proof, how do you do that?

<
16条回答
  •  青春惊慌失措
    2020-12-15 03:47

    Apart from exceptions which would be the preferred solution at runtime (and will handle crazy casting), I tend to use static compile time assertions as well.

    You can do the following:

    //this fails at compile time when the parameter to the template is false at compile time, Boost should provide a similar facility
    template  struct STATIC_ASSERTION_FAILURE;
    template <> struct STATIC_ASSERTION_FAILURE{};
    #define STATIC_ASSERT( CONDITION_ ) sizeof( STATIC_ASSERTION_FAILURE< (COLboolean)(CONDITION_) > );
    
    //
    // this define will break at compile time at locations where a switch is being
    // made for the enum. This helps when adding enums
    //
    // the max number here should be updated when a new enum is added.
    //
    // When a new enum is added, at the point of the switch (where this
    // define is being used), update the switch statement, then update
    // the value being passed into the define.
    //
    #define ENUM_SWITCH_ASSERT( _MAX_VALUE )\
       STATIC_ASSERT( _MAX_VALUE  ==  Enum_Two)
    
    enum Enum
    {
        Enum_One = 0,
        Enum_Two = 1
    };
    

    Then in your code, whenever you use the enum set:

    ENUM_SWITCH_ASSERT( Enum_Two )
    switch( e )
    {
        case Enum_One:
            do_one();
            break;
        case Enum_Two:
            do_two();
            break;
    }
    

    Now whenever you change the macro ENUM_SWITCH_ASSERT to handle a new enum value, it will break at compile time near locations that use the enum set. Helps lots when adding new cases.

提交回复
热议问题