代码之家  ›  专栏  ›  技术社区  ›  Leonid

C++中枚举int到EnUM的通用方法

  •  79
  • Leonid  · 技术社区  · 16 年前

    有没有一种通用的方法 int 到 enum 在里面 C++ ?

    如果 内景 落在 枚举 它应该返回一个 枚举 值,否则抛出 exception . 有办法写吗 一般 ? 不止一个 enum type 应该得到支持。

    背景:我有一个外部 枚举 类型和 无法控制 在源代码上。我想将此值存储在数据库中并检索它。

    9 回复  |  直到 14 年前
        1
  •  37
  •   Steve Jessop    16 年前

    最明显的是要注释枚举:

    // generic code
    #include <algorithm>
    
    template <typename T>
    struct enum_traits {};
    
    template<typename T, size_t N>
    T *endof(T (&ra)[N]) {
        return ra + N;
    }
    
    template<typename T, typename ValType>
    T check(ValType v) {
        typedef enum_traits<T> traits;
        const T *first = traits::enumerators;
        const T *last = endof(traits::enumerators);
        if (traits::sorted) { // probably premature optimization
            if (std::binary_search(first, last, v)) return T(v);
        } else if (std::find(first, last, v) != last) {
            return T(v);
        }
        throw "exception";
    }
    
    // "enhanced" definition of enum
    enum e {
        x = 1,
        y = 4,
        z = 10,
    };
    
    template<>
    struct enum_traits<e> {
        static const e enumerators[];
        static const bool sorted = true;
    };
    // must appear in only one TU,
    // so if the above is in a header then it will need the array size
    const e enum_traits<e>::enumerators[] = {x, y, z};
    
    // usage
    int main() {
        e good = check<e>(1);
        e bad = check<e>(2);
    }
    

    你需要数组保持最新 e ,如果你不是 e类 . 正如Sjoerd所说,它可能可以通过任何像样的构建系统实现自动化。

    在任何情况下,你都要面对7.2/6:

    对于emin是 最小的枚举数和emax是 最大,枚举的值 是基础类型的值 在bmin到bmax的范围内,其中bmin 和bmax分别是 最小值和最大值 能够存储emin的最小位字段 和emax。可以定义 枚举的值不是 由其任何枚举器定义。

    所以如果你不是 e类 ,您可以或不能保证 e类 实际上出现在它的定义中。

        2
  •  20
  •   John Dibling    13 年前

    丑陋。

    enum MyEnum { one = 1, two = 2 };
    
    MyEnum to_enum(int n)
    {
      switch( n )
      {
        case 1 :  return one;
        case 2 : return two;
      }
      throw something();
    }
    

    现在是真正的问题。你为什么需要这个?代码很难看,不容易编写(*?)而且不容易维护,也不容易合并到代码中。它告诉你它错了的代码。为什么要反抗?

    编辑:

    或者,假设枚举是C++中的整数类型:

    enum my_enum_val = static_cast<MyEnum>(my_int_val);
    

    但这比上面更难看,更容易出错,而且不会按你的意愿投球。

        3
  •  3
  •   Sjoerd    16 年前

    如果如您所述,这些值在数据库中,为什么不编写一个代码生成器来读取此表,并创建一个同时包含枚举和 to_enum(int) 功能?

    优势:

    • 易于添加 to_string(my_enum) 功能。
    • 几乎不需要维护
    • 数据库和代码同步
        4
  •  2
  •   luke    16 年前

    不——C++中没有内省,也没有内置的“域检查”工具。

        5
  •  2
  •   Community Mohan Dere    9 年前

    你觉得这个怎么样?

    #include <iostream>
    #include <stdexcept>
    #include <set>
    #include <string>
    
    using namespace std;
    
    template<typename T>
    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<int> _set;
    };
    
    template<typename T> std::set<int> Enum<T>::_set;
    
    class Apples: public Enum<Apples> {};
    
    class Oranges: public Enum<Oranges> {};
    
    class Proxy
    {
    public:
        Proxy(int value): _value(value) {}
    
        template<typename T>
        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"
        }
    }
    

    你可以使用我发布的代码 here 打开值。

        6
  •  1
  •   Simone    16 年前

    你不应该像你所描述的那样存在一些东西,我担心你的代码设计会有问题。

    另外,假设枚举在一个范围内,但情况并非总是如此:

    enum Flags { one = 1, two = 2, four = 4, eigh = 8, big = 2000000000 };
    

    这不在范围内:即使可能,您是否应该检查0到2^n之间的每个整数,以查看它们是否与某个枚举值匹配?

        7
  •  1
  •   janm    10 年前

    如果你准备列出你的枚举值作为模板参数,你可以用ValDad模板在C++ 11中这样做。您可以将其视为一件好事,允许您在不同的上下文中接受有效枚举值的子集;在分析来自外部源的代码时通常很有用。

    也许没有您希望的那么通用,但是检查代码本身是泛化的,您只需要指定一组值。这种方法处理间隙、任意值等。

    template<typename EnumType, EnumType... Values> class EnumCheck;
    
    template<typename EnumType> class EnumCheck<EnumType>
    {
    public:
        template<typename IntType>
        static bool constexpr is_value(IntType) { return false; }
    };
    
    template<typename EnumType, EnumType V, EnumType... Next>
    class EnumCheck<EnumType, V, Next...> : private EnumCheck<EnumType, Next...>
    {
        using super = EnumCheck<EnumType, Next...>;
    
    public:
        template<typename IntType>
        static bool constexpr is_value(IntType v)
        {
            return v == static_cast<typename std::underlying_type<EnumType>::type>(V) || super::is_value(v);
        }
    
        EnumType convert(IntType v)
        {
            if (!is_value(v)) throw std::runtime_error("Enum value out of range");
            return static_cast<EnumType>(v);
    };
    
    enum class Test {
        A = 1,
        C = 3,
        E = 5
    };
    
    using TestCheck = EnumCheck<Test, Test::A, Test::C, Test::E>;
    
    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);
    }
    
        8
  •  0
  •   Tom    12 年前

    C++“0x”替代“丑陋”版本,允许多个枚举。使用初始值设定项列表而不是开关,这在IMO中比较干净。不幸的是,这并不能解决对枚举值进行硬编码的需要。

    #include <cassert>  // assert
    
    namespace  // unnamed namespace
    {
        enum class e1 { value_1 = 1, value_2 = 2 };
        enum class e2 { value_3 = 3, value_4 = 4 };
    
        template <typename T>
        int valid_enum( const int val, const T& vec )
        {
            for ( const auto item : vec )
                if ( static_cast<int>( item ) == val ) return val;
    
            throw std::exception( "invalid enum value!" );  // throw something useful here
        }   // valid_enum
    }   // ns
    
    int main()
    {
        // generate list of valid values
        const auto e1_valid_values = { e1::value_1, e1::value_2 };
        const auto e2_valid_values = { e2::value_3, e2::value_4 };
    
        auto result1 = static_cast<e1>( valid_enum( 1, e1_valid_values ) );
        assert( result1 == e1::value_1 );
    
        auto result2 = static_cast<e2>( valid_enum( 3, e2_valid_values ) );
        assert( result2 == e2::value_3 );
    
        // test throw on invalid value
        try
        {
            auto result3 = static_cast<e1>( valid_enum( 9999999, e1_valid_values ) );
            assert( false );
        }
        catch ( ... )
        {
            assert( true );
        }
    }