std::basic_ios<CharT,Traits>::operator bool
Checks whether the stream has no errors.
# Declarations
operator /* unspecified-boolean-type */() const;
(until C++11)
explicit operator bool() const;
(since C++11)
# Notes
This conversion can be used in contexts where a bool is expected (e.g. an if condition). However, implicit conversions (e.g. to int) that can occur with bool are not allowed.
In C++98, operator bool could not be provided directly due to the safe bool problem. The initial solution in C++98 is to provide operator void*, which returns a null pointer if fail() returns true or a non-null pointer otherwise. It is replaced by the resolution of LWG issue 468, which allows Safe Bool idiom to be applied.
Since C++11, conversion functions can be explicit. The resolution of LWG issue 1094 introduced the explicit operator bool and the boolean conversion is now safe.
# Example
#include <iostream>
#include <sstream>
int main()
{
std::istringstream s("1 2 3 error");
int n;
std::cout << std::boolalpha << "s is " << static_cast<bool>(s) << '\n';
while (s >> n)
std::cout << n << '\n';
std::cout << "s is " << static_cast<bool>(s) << '\n';
}
# Defect reports
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 468 | C++98 | operator void* was provided | a conversion function to an unspecified boolean type is provided instead |