Max and min values in a C++ enum

后端 未结 6 972
广开言路
广开言路 2020-12-09 00:34

Is there a way to find the maximum and minimum defined values of an enum in c++?

相关标签:
6条回答
  • 2020-12-09 00:56

    Not automatically, but you can add artificial enum values to signify min and max values, e.g.

    typedef enum {start_of_colors=-1, eRed, eWhite, eBlue, eGray,
    end_of_colors} eListOfTags;
    
    for (eListOfTags i = start_of_colors+1; i < end_of_colors; i++) {
    .... 
    }
    
    0 讨论(0)
  • 2020-12-09 01:04

    you don't even need them, what I do is just I say for example if you have:

    enum Name{val0,val1,val2};
    

    if you have switch statement and to check if the last value was reached do as the following:

    if(selectedOption>=val0 && selectedOption<=val2){
    
       //code
    }
    
    0 讨论(0)
  • 2020-12-09 01:06

    No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,

    enum MyPretendEnum
    {
       Apples,
       Oranges,
       Pears,
       Bananas,
       First = Apples,
       Last = Bananas
    };
    

    There do not need to be named values for every value between First and Last.

    0 讨论(0)
  • 2020-12-09 01:06
      enum My_enum
        {
           FIRST_VALUE = 0,
    
           MY_VALUE1,
           MY_VALUE2,
           ...
           MY_VALUEN,
    
           LAST_VALUE
        };
    

    after definition, My_enum::LAST_VALUE== N+1

    0 讨论(0)
  • 2020-12-09 01:10

    No, not in standard C++. You could do it manually:

    enum Name
    {
       val0,
       val1,
       val2,
       num_values
    };
    

    num_values will contain the number of values in the enum.

    0 讨论(0)
  • 2020-12-09 01:20

    No. An enum in C or C++ is simply a list of constants. There is no higher structure that would hold such information.

    Usually when I need this kind of information I include in the enum a max and min value something like this:

    enum {
      eAaa = 1,
      eBbb,
      eCccc,
      eMin = eAaaa,
      eMax = eCccc
    }
    

    See this web page for some examples of how this can be useful: Stupid Enum Tricks

    0 讨论(0)
提交回复
热议问题