문제

In the C++ standard, std::ios::openmode, std::ios::fmtflags and std::ios::iostate are implementation defined. But std::ios::goodbit is standardized to be equal to zero. My question is : can these bitmask be casted to boolean values according to the standard. In other words, to test if an error flag is set, can we type :

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 */    
    }
}
도움이 되었습니까?

해결책

No this is not portable code. std::ios::iostate is a Bitmask type which, according to the C++ standard (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

If iostate is implemented in terms of the latter case, then your code will fail to compile as std::bitset has neither an operator bool nor is it implicitly convertible to an integral type (as in your case).

Note: The following fails to compile:

  std::bitset<8> b;
  return (b) ? 1 : 0;

while this works:

  std::bitset<8> b;
  return (b != 0) ? 1 : 0;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top