Reputation: 45444
This simple code
bool foo(std::istringstream&stream, std::string&single, char del)
{ return std::getline(stream,single,del); }
compiles with gcc (4.8.2) but not with clang (3.4, using libc++), which complains that there is no viable conversion from std::basic_istream<char, std::char_traits<char> >
to bool
. However, when I wrap argument to the return statement in a static_cast<bool>()
, clang is happy.
This confused me made me wonder whether the above code is well formed or not, i.e. whether gcc or clang is correct. According to cpprefernce std::getline
returns a std::basic_istream<char, std::char_traits<char> >
, which is inherited from a std::basic_ios
which has the type conversion operator bool
(since C++11, before it was a type conversion to void*
). Shouldn't this conversion operator get selected automatically? (for some reason, I'm more ready to accept that gcc is wrong than clang).
Edit I just figured out that apparently libc++ of llvm declares the conversion operator in question explicit
, deeming it invalid for the implicit conversion. Is this in line with the standard?
Upvotes: 2
Views: 1115
Reputation: 311058
As the initialization that occurs in function return is the copy-initialization then the explicit conversion operator bool
may not be applied implicitly.
From the C++ Standard
2 A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5).
So GCC has a bug.
The operator may be applied implicitly when the direct-initialization is used or in special context as the context of the if condition.
Upvotes: 1
Reputation: 171167
clang is correct. Since C++11, the conversion from std::basic_ios
to bool
is indeed required to be explicit
.
C++11, [ios.overview]
:
explicit operator bool() const;
Upvotes: 5