Bind a char to an enum type

后端 未结 3 1784
死守一世寂寞
死守一世寂寞 2021-02-20 15:44

I have a piece of code pretty similar to this:

class someclass
{
public:
enum Section{START,MID,END};
vector
Full; void ex(){ for(int i=0;i<
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-20 16:27

    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(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, 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;
             }
         }
    }
    

提交回复
热议问题