在 C++ 标准中,std::ios::openmode
、std::ios::fmtflags
和 std::ios::iostate
是实现定义的。但是 std::ios::goodbit
被标准化为等于零。我的问题是:这些位掩码能否根据标准转换为 boolean 值。换句话说,要测试是否设置了错误标志,我们可以键入:
inline void myFunction(std::ios::iostate x = std::ios::goodbit)
{
if (x) { // <- is it ok or do I have to type "if (x != std::ios::goodbit)" ?
/* SOMETHING */
}
}
最佳答案
不,这不是可移植代码。 std::ios::iostate是 Bitmask type其中,根据 C++ 标准 (17.5.2.1.3):
Each bitmask type can be implemented as an enumerated type that overloads certain operators, as an integer type, or as a bitset
如果 iostate 是根据后一种情况实现的,那么您的代码将无法编译为 std::bitset既没有运算符 bool 也不能隐式转换为整数类型(如您的情况)。
注意: 以下编译失败:
std::bitset<8> b;
return (b) ? 1 : 0;
虽然这有效:
std::bitset<8> b;
return (b != 0) ? 1 : 0;
关于C++ 流位掩码为 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773246/