array indexing (converting to integer) with scoped enumeration

前端 未结 5 448
死守一世寂寞
死守一世寂寞 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 03:05

    Alternatively you can replace your array with a map, which also means you can get rid of the maximum enum like count:

    enum class days
    {
        monday,
        tuesday,
        wednesday,
        thursday,
        friday,
        saturday,
        sunday
    };
    
    
    int main(int argc, char* argv[])
    {
        std::map days_to_string =
            {{days::monday, "Monday"},
            {days::tuesday, "Tuesday"},
            {days::wednesday, "Wednesday"},
            {days::thursday, "Thursday"},
            {days::friday, "Friday"}};
    
        for (auto day : days)
        {
            std::cout << days_to_string[day] << std::endl;
        }
    }
    

提交回复
热议问题