Rav*_*erg 7 c++ enums coding-style char
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;
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
Or any other method that could make this code "prettier". Is this possible?
Tho*_*ell 13
不幸的是,你可以做很多事情来清理它.如果您可以访问C++ 11强类型枚举器功能,那么您可以执行以下操作:
enum class Section : char {
START = 'S',
MID = 'M',
END = 'E',
};
Run Code Online (Sandbox Code Playgroud)
然后你可以做类似的事情:
std::cout << static_cast<char>(Full[i]) << std::endl;
Run Code Online (Sandbox Code Playgroud)
但是,如果您无法访问此功能,那么您可以做的事情就不多了,我的建议是拥有一个全局映射std::map<Section, char>,它将每个enum部分与一个字符相关联,或者是一个带有原型的辅助函数:
inline char SectionToChar( Section section );
Run Code Online (Sandbox Code Playgroud)
这只switch()是以更易于访问的方式实现语句,例如:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这样的情况下,你可能会很棘手并且施展你的角色.
enum Section{
START = (int)'S',
MID = (int)'M',
END = (int)'E'
};
...
inline char getChar(Section section)
{
return (char)section;
}
Run Code Online (Sandbox Code Playgroud)