Bind a char to an enum type

╄→гoц情女王★ 提交于 2019-12-10 03:59:51

问题


I have a piece of code pretty similar to this:

class someclass
{
public:
enum Section{START,MID,END};
vector<Section> Full;
void ex(){
    for(int i=0;i<Full.size();i++)
    {
        switch (Full[i])
        {
        case START :
                  cout<<"S";
                  break;
        case MID :
                  cout<<"M";
                  break;
        case END:
            cout<<"E";
            break;
        }
    }
    }
};

Now imagine I have much more enum types and their names are longer.... well what i get is not a very good looking code and i was wondering if it possible to bind a specific char to an enum type and maybe do something like this:

for(int i=0;i<Full.size();i++)
    {
        cout<(Full[i]).MyChar();
    }

Or any other method that could make this code "prettier". Is this possible?


回答1:


Unfortunately there is not much you can do to clean this up. If you have access to the C++11 strongly typed enumerator feature, then you could do something like the following:

enum class Section : char {
     START = 'S',
     MID = 'M',
     END = 'E',
};

And then you could do something like:

std::cout << static_cast<char>(Full[i]) << std::endl;

However, if you do not have access to this feature then there's not much you can do, my advice would be to have either a global map std::map<Section, char>, which relates each enum section to a character, or a helper function with the prototype:

inline char SectionToChar( Section section );

Which just implements the switch() statement in a more accessible way, e.g:

inline char SectionToChar( Section section ) {
     switch( section )
     {
     default:
         {
             throw std::invalid_argument( "Invalid Section value" );
             break;
         }
     case START:
         {
             return 'S';
             break;
         }
     case MID:
         {
             return 'M';
             break;
         }
     case END:
         {
             return 'E';
             break;
         }
     }
}



回答2:


In a situation like this you could be tricky and cast your chars.

enum Section{
    START = (int)'S',
    MID   = (int)'M',
    END   = (int)'E'
};

...

inline char getChar(Section section)
{
    return (char)section;
}



回答3:


I think the best solution in this case would be to use a map:

#include <iostream>
#include <map>
class someclass
{
    public:
    enum Section{START = 0,MID,END};
    map<Section,string> Full;

    // set using Full[START] = "S", etc

    void ex(){
        for(int i=0;i<Full.size();i++)
        {
            cout << Full[i];
        }
    }
};


来源:https://stackoverflow.com/questions/17095639/bind-a-char-to-an-enum-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!