Generic way to cast int to enum in C++

前端 未结 8 2120
[愿得一人]
[愿得一人] 2020-12-04 11:26

Is there a generic way to cast int to enum in C++?

If int falls in range of an enum it should return

8条回答
  •  星月不相逢
    2020-12-04 11:54

    What do you think about this one?

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    template
    class Enum
    {
    public:
        static void insert(int value)
        {
            _set.insert(value);
        }
    
        static T buildFrom(int value)
        {
            if (_set.find(value) != _set.end()) {
                T retval;
                retval.assign(value);
                return retval;
            }
            throw std::runtime_error("unexpected value");
        }
    
        operator int() const { return _value; }
    
    private:
        void assign(int value)
        {
            _value = value;
        }
    
        int _value;
        static std::set _set;
    };
    
    template std::set Enum::_set;
    
    class Apples: public Enum {};
    
    class Oranges: public Enum {};
    
    class Proxy
    {
    public:
        Proxy(int value): _value(value) {}
    
        template
        operator T()
        {
            T theEnum;
            return theEnum.buildFrom(_value);
        }
    
        int _value;
    };
    
    Proxy convert(int value)
    {
        return Proxy(value);
    }
    
    int main()
    {    
        Apples::insert(4);
        Apples::insert(8);
    
        Apples a = convert(4); // works
        std::cout << a << std::endl; // prints 4
    
        try {
            Apples b = convert(9); // throws    
        }
        catch (std::exception const& e) {
            std::cout << e.what() << std::endl; // prints "unexpected value"
        }
        try {
            Oranges b = convert(4); // also throws  
        }
        catch (std::exception const& e) {
            std::cout << e.what() << std::endl; // prints "unexpected value"
        }
    }
    

    You could then use code I posted here to switch on values.

提交回复
热议问题