Pregunta

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 */    
    }
}
¿Fue útil?

Solución

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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top