array indexing (converting to integer) with scoped enumeration

前端 未结 5 444
死守一世寂寞
死守一世寂寞 2020-12-30 02:10

C++11 scoped enumerators (enum class syntax) do not convert to integers so they cannot be used directly as array indexes.

What\'s the best way to get th

5条回答
  •  离开以前
    2020-12-30 02:58

    The original question related to using the enumeration as an array index. Instead of trying to turn the enumeration into an index for an array, build an array that accepts the enumeration as its index:

    template  (largest_enum)>
    class EnumeratedArray {
        ValueType underlying [static_cast  (largest_enum)];
    public:
        using value_type = ValueType;
        using enumeration_type = Enumeration;
        EnumeratedArray () {
            for (int i = 0; i < largest; i++) {
                underlying [i] = ValueType {};
            }
        }
        inline ValueType &operator[] (const Enumeration index) {
            assert (static_cast  (index) >= 0 && static_cast  (index) < largest);
            return underlying [static_cast  (index)];
        }
        inline const ValueType &operator[] (const Enumeration index) const {
            assert (static_cast  (index) >= 0 && static_cast  (index) < largest);
            return underlying [static_cast  (index)];
        }
    };
    

    So now, with the earlier ducks example:

    enum class ducks { huey, dewey, louie, count };
    EnumeratedArray duck_height;
    duck_height [ducks::huey] = 42.0;
    

    Had ducks values been capitalized differently, the size could default:

    enum class Ducks { Huey, Dewey, Louie, Count };
    EnumeratedArray duck_height;
    duck_height [Ducks::Huey] = 42.0;
    

    In addition to avoiding enum contortions, since the to-index conversion is hidden in the implementation, the enum doesn't risk erroneously becoming an integer at other points in your code, nor can you inadvertently index the array via integer.

    EnumeratedArray is used in pianod2, in src/common. A more extensive version there includes template magic to only explicitly default-initialize plain-old datatypes, a constructor to initialize all elements to a specified value, and doc comments.

提交回复
热议问题