How to check if enum value is valid?

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

    Kinda necro, but ... makes a RANGE check of int into first/last enum values (can be combined with janm's idea to make exact checks), C++11:

    Header:

    namespace chkenum
    {
        template 
        struct RangeCheck
        {
        private:
            typedef typename std::underlying_type::type val_t;
        public:
            static
            typename std::enable_if::value, bool>::type
            inrange(val_t value)
            {
                return value >= static_cast(begin) && value <= static_cast(end);
            }
        };
    
        template
        struct EnumCheck;
    }
    
    #define DECLARE_ENUM_CHECK(T,B,E) namespace chkenum {template<> struct EnumCheck : public RangeCheck {};}
    
    template
    inline
    typename std::enable_if::value, bool>::type
    testEnumRange(int val)
    {
        return chkenum::EnumCheck::inrange(val);
    }
    

    Enum declaration:

    enum MinMaxType
    {
         Max = 0x800, Min, Equal
    };
    DECLARE_ENUM_CHECK(MinMaxType, MinMaxType::Max, MinMaxType::Equal);
    

    Usage:

    bool r = testEnumRange(i);
    

    Mainly difference of above proposed it that test function is dependent on enum type itself only.

提交回复
热议问题