Converting stream to bool doesn't work on other compiler

Why does it work with libstdc ++ , but with libc ++ it will fail? On gcc it also works:

bool b = std::cin;

      

+3


source to share


2 answers


You must add the standard language and compiler you are compiling with.

Prior to C ++ 11, std::basic_ios

had operator void*

, since C ++ 11 has instead explicit operator bool

.

The second one is explicit, that is, an implicit conversion like in your example cannot use it.



libstdc ++ from the GNU project still unconditionally contains the pre-C ++ conversion (version 4.9.1):

operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }

      

Bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56193 RESOLVED-FIXED since 2014-09-24, so the next release should be fixed.

+7


source


As per the C ++ standard (13.3.1.5 Initialization with a conversion function, page # 1)

The transformation functions S and its base classes are considered. Those implicit conversion functions that are not hidden within S and the output type T or a type that can be converted to type T via the standard conversion sequence (13.3.3.1.1) are candidate functions. For direct initialization, those explicit conversion functions that are not hidden within S and yield a type T or a type that can be converted to type T with qualifying conversion (4.4) are also a function candidate.

The class std::basic_ios

has an explicit conversion function operator bool

. As this ad



bool b = std::cin;

      

does not use direct initialization (there is copy initialization), then it seems that this is a compiler error, that is, the declaration does not compile.

0


source







All Articles