Search code examples
c++enumscountdefault

What is the best way for non sequencial integer c++ enums


Following the C++ enum pattern I already described here, I was trying to do a similar thing but this time the sequence of values I want to use is not comprehended of continuous integer numbers.

The code is obviously wrong:

class Rotations
{
    enum PossibleIndexes
    {
        ZERO,
        PLUS180,
        PLUS90,
        MINUS90
    };


    enum PossibleValues
    {
        ZERO= 0,
        PLUS180= 180,
        PLUS90= 90,
        MINUS90= -90
    };

    static int Count() { return MINUS90 + 1; }

    static PossibleValues Default(){ return ZERO; }
};

as there will be conflicts between elements inherent of the two enums.

So my question is: What is the best approach to implement a fixed number of hardcoded Rotations{0, 180, 90, -90} which has also a Default and a Count functionality?


Solution

  • Due to the limitations of Visual C++ 2010 Compilation Toolkit (not fully C++11 compliant), I had to surrender myself to inferior approaches.

    The post at https://stackoverflow.com/a/15961043/383779 also suggested me an interesting approach for getting the values.

    class Rotations
    {
    public:
        typedef enum
        {
            ZERO= 0,
            PLUS180= 180,
            PLUS90 = 90,
            MINUS90 = -90
        }PossibleValues;
    
        static const PossibleValues PossibleValuesCollection(int index) {
            static const PossibleValues values[] = { ZERO, PLUS180, PLUS90, MINUS90 };
    
            return values[index];
        }
    
        static int Count() { return 4; }
        static PossibleValues Default(){ return ZERO; }
    };