How to check if enum value is valid?

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

    In C++ 11 there is a better way if you are prepared to list your enum values as template parameters. You can look at this as a good thing, allowing you to accept subsets of the valid enum values in different contexts; often useful when parsing codes from external sources.

    A possible useful addition to the example below would be some static assertions around the underlying type of EnumType relative to IntType to avoid truncation issues. Left as an exercise.

    #include 
    
    template class EnumCheck;
    
    template class EnumCheck
    {
    public:
        template
        static bool constexpr is_value(IntType) { return false; }
    };
    
    template
    class EnumCheck : private EnumCheck
    {
        using super = EnumCheck;
    
    public:
        template
        static bool constexpr is_value(IntType v)
        {
            return v == static_cast(V) || super::is_value(v);
        }
    };
    
    enum class Test {
        A = 1,
        C = 3,
        E = 5
    };
    
    using TestCheck = EnumCheck;
    
    void check_value(int v)
    {
        if (TestCheck::is_value(v))
            printf("%d is OK\n", v);
        else
            printf("%d is not OK\n", v);
    }
    
    int main()
    {
        for (int i = 0; i < 10; ++i)
            check_value(i);
    }
    

提交回复
热议问题