Converting a stream to bool doesn't work on another compiler - c++

Why with libstdc++ this works but with libc++ it fails? On gcc it also works:
bool b = std::cin;

You should add the language standard and compiler you compile with.
Until C++11, std::basic_ios had operator void*, since C++11 it has explicit operator bool instead.
The second one is explicit, meaning 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); }
The bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56193 is RESOLVED-FIXED since 2014-09-24, so the next release should be corrected.

According to the C++ Standard (13.3.1.5 Initialization by conversion function, p.#1)
The conversion functions of S and its base classes are considered.
Those non-explicit conversion functions that are not hidden within S
and yield type T or a type that can be converted to type T via a
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 type T or a type that can be converted
to type T with a qualification conversion (4.4) are also candidate
functions.
Class std::basic_ios has explicit conversion function operator bool. As
this declaration
bool b = std::cin;
does not use the direct initialization (there is the copy initialization) then it seems it is a bug of the compiler, that is the declaration shall not be compiled.

Related

Overload resolution of user-defined type conversion

I considered a type conversion from one type to the other, which are defined by two way, i.e., type conversion constructor and type conversion function.
struct to_type;
struct from_type{
operator to_type()const;
};
struct to_type{
to_type() = default;
to_type(const from_type&){}
};
from_type::operator to_type()const{return to_type();}
int main(){
from_type From;
to_type To;
To = From;
return 0;
}
gcc (v13.0.0, but seems to be same even in v4.9.4) don't throw any error and just call type conversion constructor in the above code.
On the other hand, clang (v16.0.0, but seems to be same even in v7.6.0) throw a "ambiguous" compile error like the following.
prog.cc:14:10: error: reference initialization of type 'to_type &&' with initializer of type 'from_type' is ambiguous
To = From;
^~~~
prog.cc:3:4: note: candidate function
operator to_type()const;
^
prog.cc:7:4: note: candidate constructor
to_type(const from_type&){}
^
prog.cc:5:8: note: passing argument to parameter here
struct to_type{
^
1 error generated.
It seems to be so curious that two major compiler show different result for this simple code. Is either compiler don't match with the standard for C++? I guess this overload resolution related to [over.ics.rank], but I could not concluded which compiler's behavior match to the standard.
Or do my source code contains undefined behavior?
[ADD 2022-12-21T00:20Z]
Following the comment by Artyer, I tried -pedantic compile option for gcc, and now gcc also output error message.
prog.cc: In function 'int main()':
prog.cc:14:10: error: conversion from 'from_type' to 'to_type' is ambiguous
14 | To = From;
| ^~~~
prog.cc:9:1: note: candidate: 'from_type::operator to_type() const'
9 | from_type::operator to_type()const{return to_type();}
| ^~~~~~~~~
prog.cc:7:4: note: candidate: 'to_type::to_type(const from_type&)'
7 | to_type(const from_type&){}
| ^~~~~~~
prog.cc:5:8: note: initializing argument 1 of 'constexpr to_type& to_type::operator=(to_type&&)'
5 | struct to_type{
| ^~~~~~~
This suggests that at least the default behavior of gcc without -pedantic don't match with the requirements of C++ standard for this source code.
In this case clang is right, this behaviour is defined in [over.best.ics.general], and standard even mentions that such a conversion is ambiguous explicitly under the sample code to [over.best.ics.general]/10 (the scenario under the link is in fact considers another kind of ambiguity, but resolution to user-defined pair of conversion constructor and conversion operator is one of the candidates, so I removed the part of the code with another candidate):
class B;
class A { A (B&);};
class B { operator A (); };
...
void f(A) { }
...
B b;
f(b); // ... an (ambiguous) conversion b → A (via constructor or conversion function)
In order to break the name resolution down, I'd like to represent the conversion sequence (To = From;) as an assignment operator function:
to_type& operator=(to_type&& param) { } // defined implicitly by the compiler
The actual conversion happens when param needs to get into existence out of From argument of type from_type. The compiler then needs to decide step by step:
Which type the conversion sequence from from_type to to_type&& is of? (standard/user defined/ellipsis):
The types from_type is user defined, but to_type&& is of reference type, and reference binding could be considered identity (i.e. standard) conversion. However it's not the case, since from_type and to_type are not the same and cannot be bound directly ([over.ics.ref]/2):
When a parameter of reference type is not bound directly to an argument expression, the conversion sequence is the one required to convert the argument expression to the referenced type according to [over.best.ics].
Without reference binding there is no any other standard conversion sequence that may suit here. Let's consider user-defined conversion. [over.ics.user] gives us the following definition:
A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion ([class.conv]) followed by a second standard conversion sequence. If the user-defined conversion is specified by a constructor ([class.conv.ctor]), the initial standard conversion sequence converts the source type to the type of the first parameter of that constructor. If the user-defined conversion is specified by a conversion function, the initial standard conversion sequence converts the source type to the type of the implicit object parameter of that conversion function.
This sounds about right to me: we need to convert from_type argument to to_type temporary in order for to_type&& to bind to the argument, thus the sequence is either
from_type -> const from_type& for the converting constructor argument to_type(const from_type&) -> to_type&& for the move-assignment operator of to_type& operator=(to_type&&)
OR
from_type -> implicit-object-parameter of type const from_type& for conversion function operator to_type() const -> to_type&& for the move-assignment operator of to_type& operator=(to_type&&).
Now we have two possible conversion sequences of the same kind (user-defined). For this scenario [over.best.ics.general]/10 says the following:
If there are multiple well-formed implicit conversion sequences converting the argument to the parameter type, the implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence designated the ambiguous conversion sequence. For the purpose of ranking implicit conversion sequences as described in [over.ics.rank].
The Ranking implicit conversion sequences documentation then gives the following clues about deciding on which conversion (of the same sequence type) should take precedence for user-defined sequences ([over.ics.rank]/3.3, emphasis mine):
User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2
Here we go, for both scenarios (with the converting constructor and the conversion function) the second standard conversion is of the same type (a temporary of type to_type to to_type&&), thus the operations are indistinguishable.
Clang is wrong in rejecting the program because an overload with T&& is better match than an overload with const int&. Note that gcc is also wrong because it uses the copy constructor instead of operator to_type() const. See demo. Only msvc is right and both gcc and clang are wrong. MSVC correctly uses the conversion function.
S1 S2
int int&& indistinguishable
int const int& indistinguishable
int&& const int& S1 better
Consider the contrived example:
#include <iostream>
struct to_type;
struct from_type{
operator to_type()const;
};
struct to_type{
to_type() = default;
to_type(const from_type&){std::cout <<"copy ctor";}
};
from_type::operator to_type()const{
std::cout<<"to_type operator";
return to_type();}
void f(to_type&&){}
int main(){
from_type From;
f(From); //valid and this should use from_type::operator to_type() const
}
Demo
The above program is rejected by clang(with the same error as you're getting) but accepted by gcc and msvc. Note that even though gcc accepts the above program it is still wrong because the conversion function should be used instead of the copy ctor. MSVC on the other hand correctly uses the conversion function.

Why is == operator overload of enum ambiguous in MSVC

The following code compiles fine on all compilers I've checked (clang, mingw, g++) other than MSVC.
enum class Foo{BAR};
bool operator==(Foo a, Foo b)
{
return (int)a & (int)b;
}
int main(int argc, char *argv[])
{
Foo::BAR==Foo::BAR;
return 0;
}
MSVC fails with the following error:
>main.cpp(10): error C2593: 'operator ==' is ambiguous
>main.cpp(3): note: could be 'bool operator ==(Foo,Foo)'
>main.cpp(10): note: while trying to match the argument list '(Foo, Foo)'
Any insight would be great, I've been scratching my head about this all day.
My version of MSVC is 14.0 however I've tested it online with version Version 19.00.23506 and the same error appears.
The error does not apear with version 19.11.25331.0 however.
Compiler bug then?
For enumerations, there's a built-in comparison operator. When you define yours, the built-in is supposed to be hidden automatically.
[over.built/1]
The candidate operator functions that represent the built-in operators
defined in Clause [expr] are specified in this subclause. These
candidate functions participate in the operator overload resolution
process as described in [over.match.oper] and are used for no other
purpose. [ Note: Because built-in operators take only operands with
non-class type, and operator overload resolution occurs only when an
operand expression originally has class or enumeration type, operator
overload resolution can resolve to a built-in operator only when an
operand has a class type that has a user-defined conversion to a
non-class type appropriate for the operator, or when an operand has an
enumeration type that can be converted to a type appropriate for the
operator. Also note that some of the candidate operator functions
given in this subclause are more permissive than the built-in
operators themselves. As described in [over.match.oper], after a
built-in operator is selected by overload resolution the expression is
subject to the requirements for the built-in operator given in Clause
[expr], and therefore to any additional semantic constraints given
there. If there is a user-written candidate with the same name and
parameter types as a built-in candidate operator function, the
built-in operator function is hidden and is not included in the set of
candidate functions. — end note ]
To answer your question, yes, it seems like a compiler bug.

istream to bool conversion: when is it available?

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?
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;
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.

Non-const copy constructor and implicit conversions on return value

Consider the following C++ code:
struct B { };
struct A
{
A(int);
A(A&); // missing const is intentional
A(B);
operator B();
};
A f()
{
// return A(1); // compiles fine
return 1; // doesn't compile
}
This compiles fine on MSVC++ 2010 (in fact, on MSVC it even works if I remove B altogether). It doesn't on GCC 4.6.0:
conv.cpp: In function ‘A f()’:
conv.cpp:13:9: error: no matching function for call to ‘A::A(A)’
conv.cpp:13:9: note: candidates are:
conv.cpp:6:2: note: A::A(B)
conv.cpp:6:2: note: no known conversion for argument 1 from ‘A’ to ‘B’
conv.cpp:5:2: note: A::A(A&)
conv.cpp:5:2: note: no known conversion for argument 1 from ‘A’ to ‘A&’
conv.cpp:4:2: note: A::A(int)
conv.cpp:4:2: note: no known conversion for argument 1 from ‘A’ to ‘int’
What's confusing me is the message no known conversion for argument 1 from ‘A’ to ‘B’. How can this be true considering that A::operator B() is very well defined?
Because you cannot do more than one implicit conversion. You would have to go A::A(A::A(int)::operator B()) to make that work, and that's way too many steps for the compiler to figure out on it's own.
I don't think that "too many steps to figure on its own" as DeadMG pointed out is the reason. I've had constructs with 3-4 conversions, and the compiler always figured them out just fine.
I believe the problem is rather that the compiler is not allowed to convert a const reference to a non-constreference on its own behalf (it is only allowed to do that when you explicitly tell it with a cast).
And since the reference to the temporary object that is passed to the copy constructor is const, but the copy constructor is not, it doesn't find a suitable function.
EDIT: I didn't find any "real" code (see comments below) but constructed a multi-zigzag-convert example that actually compiles without errors under gcc 4.5. Note that this compiles just fine with -Wall -Wextra too, which frankly surprises me.
struct B
{
signed int v;
B(unsigned short in) : v(in){}
};
struct C
{
char v;
C(int in) : v(in){}
};
struct A
{
int v;
A(B const& in) : v(in.v){}
operator C() { return C(*this); }
};
enum X{ x = 1 };
int main()
{
C c = A(x);
return 0;
}
The error is quite clear on the list of candidates that were rejected. The problem is that implicit conversion sequences involving a user defined conversion in the C++ language are limited to a single user defined conversion:
§13.3.3.1.2 [over.ics.user]/1 A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion (12.3) followed by a second standard conversion sequence.
The standard conversion sequences are defined in §4[conv]:
[...] A standard conversion sequence is a sequence of standard conversions in the following order
Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.
Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.
Zero or one qualification conversion.
The problem is that your code cannot get from point a) int rvalue to point b) B by applying a single user defined conversion.
In particular, all conversion sequences that are available start with a user defined conversion (implicit constructor A(int)) that yield an A rvalue. From there, the rvalue cannot be bound to a non-const reference to call A::A( A& ), so that path is discarded. All the other paths require a second user defined conversion that is not allowed, and in fact the only other path that would get us to point b) requires two other user defined conversions for a total of 3.
The error lists all the potential candidates to be used, and why they cannot be used. It lists the conversion from B because its one of the constructors, but it doesn't know how to use it in this case, so it doesn't.

C++ implicit conversions

Several comments on a recent answer of mine, What other useful casts can be used in C++, suggest that my understanding of C++ conversions is faulty. Just to clarify the issue, consider the following code:
#include <string>
struct A {
A( const std::string & s ) {}
};
void func( const A & a ) {
}
int main() {
func( "one" ); // error
func( A("two") ); // ok
func( std::string("three") ); // ok
}
My assertion was that the the first function call is an error, becauuse there is no conversion from a const char * to an A. There is a conversion from a string to an A, but using this would involve more than one conversion. My understanding is that this is not allowed, and this seems to be confirmed by g++ 4.4.0 & Comeau compilers. With Comeau, I get the following error:
"ComeauTest.c", line 11: error: no suitable constructor exists
to convert from "const char [4]" to "A"
func( "one" ); // error
If you can point out, where I am wrong, either here or in the original answer, preferably with reference to the C++ Standard, please do so.
And the answer from the C++ standard seems to be:
At most one user-defined conversion
(constructor or conversion function)
is implicitly applied to a single value.
Thanks to Abhay for providing the quote.
I think the answer from sharptooth is precise. The C++ Standard (SC22-N-4411.pdf) section 12.3.4 titled 'Conversions' makes it clear that only one implicit user-defined conversion is allowed.
1 Type conversions of class objects can be specified by
constructors and by conversion
functions. These
conversions are called user-defined conversions and are used
for implicit type conversions (Clause
4), for
initialization (8.5), and for explicit type conversions (5.4,
5.2.9).
2 User-defined conversions are applied only where they are
unambiguous (10.2, 12.3.2).
Conversions obey the
access control rules (Clause 11). Access control is applied after
ambiguity resolution (3.4).
3 [ Note: See 13.3 for a discussion of the use of conversions
in function calls as well as examples
below. —end
note ]
4 At most one user-defined conversion (constructor or conversion
function) is implicitly applied to a
single
value.
That's true, only one implicit conversion is allowed.
Two conversions in a row may be performed with a combination of a conversion operator and a parameterized constructor but this causes a C4927 warning - "illegal conversion; more than one user-defined conversion has been implicitly applied" - in VC++ for a reason.
As the consensus seems to be already: yes you're right.
But as this question / answers will probably become the point of reference for C++ implicit conversions on stackoverflow I'd like to add that for template arguments the rules are different.
No implicit conversions are allowed for arguments that are used for template argument deduction. This might seem pretty obvious but nevertheless can lead to subtle weirdness.
Case in point, std::string addition operators
std::string s;
s += 67; // (1)
s = s + 67; // (2)
(1) compiles and works fine, operator+= is a member function, the template character parameter is already deduced by instantiating std::string for s (to char). So implicit conversions are allowed (int -> char), results in s containing the char equivalent of 67, e.g. in ASCII this would become 'C'
(2) gives a compiler error as operator+ is declared as a free function and here the template character argument is used in deduction.
The C++ Programming Language (4th. ed.) (section 18.4.3) says that
only one level of user-defined
implicit conversion is legal
That "user-defined" part makes it sound like multiple implicit conversions may be allowed if some are between native types.