“enum class” emulation or solid alternative for MSVC 10.0

后端 未结 3 581
无人共我
无人共我 2020-12-05 11:30

I\'m looking for a hacky kind of solution to the following problem: GCC 4.4+ accepts the following c++0x code:

enum class my_enum
{
    value1,
    value2
};         


        
3条回答
  •  天命终不由人
    2020-12-05 12:26

    I have been fighting for a whole day to find a truly optimal solution, but there doesn't seem to be one. I need my enum that is

    1. Not implicitly convertible to an integral type
    2. Usable in a switch statement
    3. Usable as non-type template parameter

    In have come up with the following code, built upon Howard Hinnant's solution:

    struct DataType
    {
        struct integral {
            enum type { None, Single, Double, Int };
        };
    
        typedef typename integral::type integral_type;
    
        explicit DataType(integral_type v) : val(v) {}
        integral_type integral_value() const { return val; }
    
        bool operator==(const DataType& s) const { return val == s.val; }
        bool operator!=(const DataType& s) const { return val != s.val; }
    
        static const DataType None;
        static const DataType Single;
        static const DataType Double;
        static const DataType Int;
    
    private:
        integral_type val;
    };
    

    In the .cpp file:

    const DataType DataType::None   (DataType::integral::None);
    const DataType DataType::Single (DataType::integral::Single);
    const DataType DataType::Double (DataType::integral::Double);
    const DataType DataType::Int    (DataType::integral::Int);
    

    As non-type template parameter:

    template 
    struct DataTypeTraits;
    
    template <>
    struct DataTypeTraits
    {
        enum { size = 4 };
    };
    

    In a switch:

    size_t get_size(DataType type)
    {
        switch (type.integral_value()) {
            case DataType::integral::Single:  return DataTypeTraits::size;
            case DataType::integral::Double:  return DataTypeTraits::size;
            case DataType::integral::Int:     return DataTypeTraits::size;
            default:                          throw  std::logic_error("Unknown data type.");
        }
    }
    

    Not particularly great, but that's as good as it gets, I guess...

提交回复
热议问题