我想替换 i/ostream 的 bitshift bool 重载。当前的实现只接受“0”或“1”的输入字符串,只输出“0”或“1”。我想制作一个考虑其他序列的布尔重载,例如“t”、“true”、“f”、“false”等……有没有办法做到这一点,即使它仅限于有限的范围?这是我要使用的代码:
inline std::ostream& operator << (std::ostream& os, bool b)
{
return os << ( (b) ? "true" : "false" );
}
inline std::istream& operator >> (std::istream& is, bool& b)
{
string s;
is >> s;
s = Trim(s);
const char* true_table[5] = { "t", "T", "true" , "True ", "1" };
const char* false_table[5] = { "f", "F", "false", "False", "0" };
for (uint i = 0; i < 5; ++i)
{
if (s == true_table[i])
{
b = true;
return is;
}
}
for (uint i = 0; i < 5; ++i)
{
if (s == false_table[i])
{
b = false;
return is;
}
}
is.setstate(std::ios::failbit);
return is;
}