C++ 流位掩码为 boolean 值?

标签 c++ boolean standards-compliance bitmask

在 C++ 标准中,std::ios::openmodestd::ios::fmtflagsstd::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::iostateBitmask 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/

相关文章:

c++ - 这个模板语法可以改进吗?

c++ - Internet Explorer 闪烁的子窗口

android - 如何在 Android 中 ping 服务器?

c++ - 曾经有效的代码不再有效?视觉 C++ 2010

c++ - void 函数允许返回 "nothing"吗?

c# - 为什么 integer == null 在 C# 中是一个有效的 boolean 表达式?

android - 如何让 Android 翻译 boolean 值?

ftp - 哪些FTP传输模式被广泛使用?

html - 棘手的 CSS 布局