Why is == operator overload of enum ambiguous in MSVC - c++

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.

Related

Difference in behavior of pointer-to-member access operators

In C++, I'm searching for the crucial sections of the standard
explaining the subtle difference in behavior I've observed between the
language's two pointer-to-member access operators, .* and ->*.
According to my test program shown below, whilst ->* seems to allow its
right-hand expression to be of any type implicitly convertible to
pointer to member of S, .* does not so. When compiling with
gcc and clang, both compilers yield errors for the line marked '(2)'
stating that my class Offset cannot be used as a member pointer.
Test Program
https://godbolt.org/z/46nMPvKxE
#include <iostream>
struct S { int m; };
template<typename C, typename M>
struct Offset
{
M C::* value;
operator M C::* () { return value; } // implicit conversion function
};
int main()
{
S s{42};
S* ps = &s;
Offset<S, int> offset{&S::m};
std::cout << ps->*offset << '\n'; // (1) ok
std::cout << s.*offset << '\n'; // (2) error
std::cout.flush();
}
Compiler Output
GCC 12.2:
'offset' cannot be used as a member pointer, since it is of type 'Offset<S, int>'
clang 15.0:
right hand operand to .* has non-pointer-to-member type 'Offset<S, int>'
Program Variation
In order to prove that ->* actually performs an implicit conversion using Offset's
conversion function in the test program shown above, I declared it explicit for test purposes,
explicit operator M C::* () { return value; } // no longer implicit conversion function
resulting in the compilers to also yield errors for the line marked '(1)':
GCC 12.2:
error: no match for 'operator->*' (operand types are 'S*' and 'Offset<S, int>')
note: candidate: 'operator->*(S*, int S::*)' (built-in)
note: no known conversion for argument 2 from 'Offset<S, int>' to 'int S::*'
clang 15.0:
error: right hand operand to ->* has non-pointer-to-member type 'Offset<S, int>'
Research
Whilst there is a well-documented difference between the two operators in that
->* is overloadable and .* is not, my code obviously does not make use of this option
but rather relies on the built-in operator ->* defined for raw pointer type S*.
Besides differences in overloadability, I merely found documentation stating the similarity
of the expressions. Cited from the standard (https://open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4868.pdf):
[7.6.4.2] The binary operator .* binds its second operand, which shall be of type “pointer to member of T” to its first
operand, which shall be a glvalue of class T or of a class of which T is an unambiguous and accessible base
class. The result is an object or a function of the type specified by the second operand.
[7.6.4.3] [...] The expression E1->E2 is converted into the equivalent form ((E1)).*E2.
And cited from cppreference.com (https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_pointer-to-member_access_operators):
The second operand of both operators is an expression of type pointer to member ( data or function) of T or pointer to member of an unambiguous and accessible base class B of T.
The expression E1->*E2 is exactly equivalent to (*E1).*E2 for built-in types; that is why the following rules address only E1.*E2.
Nowhere have I found a notion of conversion of the right hand operand.
Question
What have I overlooked? Can someone point me to an explanation of this difference in behavior?
When overloadable operators are used and at least one operand is of class or enumeration type, overload resolution is performed using a candidate set that includes built-in candidates ([over.match.oper]/3) - for ->* in particular, see [over.built]/9.
In this case, a built-in candidate is selected, so the implicit conversion is applied to the second operand, and then ->* is interpreted as the built-in operator ([over.match.oper]/11).
With .*, there's no overload resolution at all, so no implicit conversion either.

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

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.

How to overload operator + for const char* and int

I know this is silly and ugly, but I'm migrating some code automatically. My source language allows implicit conversion between strings and ints, and for example this is allowed:
var = "hello " + 2
print(var) # prints "hello 2"
How can I in C++ overload the + operator for const char* and int? I'm getting the error:
error: ‘std::string operator+(char* const&, int)’ must have an
argument of class or enumerated type
What you are asking for is illegal
To legally overload an operator at least one of the operands involved has to be a user-defined type. Since neither char* nor int is user-defined, what you are trying to accomplish isn't possible.
This, what you are trying to do, is intentionally, and explicitly, disallowed in the standard. Don't you think it would be weird if suddenly 1+3 = 42 because someone "clever" have defined an overload for operator+(int, int)?
What does the Standard say? (n3337)
13.3.1.2p1-2 Operators in expressions [over.match.oper]
If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.
If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be neccessary to convert the operand to a type that is appropriate for a built-in operator.
( Note: The wording is the same in both C++03, and the next revision of the standard; C++14 )

Unary + on pointers

I was just browsing through the draft of the C++11 standard and found the following puzzling statement (§13.6/8):
For every type T there exist candidate operator functions of the form
T* operator+(T*);
How should this "unary +" operator on pointer be understood? Is this just a no-op in the normal case, which can nevertheless be overloaded? Or is there some deeper point I am missing here?
The + on pointers is a noop except for turning things to rvalues. It sometimes is handy if you want to decay arrays or functions
int a[] = { 1, 2, 3 };
auto &&x = +a;
Now x is an int*&& and not an int(&)[3]. If you want to pass x or +a to templates, this difference might become important. a + 0 is not always equivalent, consider
struct forward_decl;
extern forward_decl a[];
auto &&x = +a; // well-formed
auto &&y = a + 0; // ill-formed
The last line is ill-formed, because adding anything to a pointer requires the pointer's pointed-to class type to be completely defined (because it advances by sizeof(forward_decl) * N bytes).
The answer to your question is just a page above the quote you cited — §13.6/1:
The candidate operator functions that represent the built-in operators defined in Clause 5 are specified in this subclause. These candidate functions participate in the operator overload resolution process as described in 13.3.1.2 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 13.3.1.2, 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 5, 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 ]
Well, you could overload it do do whatever you want, but it's just there for symmetry with the unary - operator. As you mention, it's just a no-op most of the time.

Should this compile? Overload resolution and implicit conversions

This example seems to compile with VC10 and gcc (though my version of gcc is very old).
EDIT: R. Martinho Fernandez tried this on gcc 4.7 and the behaviour is still the same.
struct Base
{
operator double() const { return 0.0; }
};
struct foo
{
foo(const char* c) {}
};
struct Something : public Base
{
void operator[](const foo& f) {}
};
int main()
{
Something d;
d["32"];
return 0;
}
But clang complains:
test4.cpp:19:6: error: use of overloaded operator '[]' is ambiguous (with operand types 'Something' and 'const char [3]')
d["32"]
~^~~~~
test4.cpp:13:10: note: candidate function
void operator[](const foo& f) {}
^
test4.cpp:19:6: note: built-in candidate operator[](long, const char *)
d["32"]
^
test4.cpp:19:6: note: built-in candidate operator[](long, const restrict char *)
test4.cpp:19:6: note: built-in candidate operator[](long, const volatile char *)
test4.cpp:19:6: note: built-in candidate operator[](long, const volatile restrict char *)
The overload resolution is considering two possible functions from looking at this expression:
calling Something::operator[] (after a user defined conversion)
calling built in operator for const char* (think "32"[d]) (after a user defined conversion and standard conversion double to long).
If I had written d["32"] as d.operator[]("32"), then overload resolution won't even look at option 2, and clang will also compile fine.
EDIT: (clarification of questions)
This seems to be a complicated area in overload resolution, and because of that I'd appreciate very much answers that explain in detail the overload resolution in this case, and cite the standard (if there's some obscure/advanced likely to be unknown rule).
If clang is correct, I'm also interested in knowing why the two are ambiguous / one is not preferred over another. The answer likely would have to explain how overload resolution considers implicit conversions (both user defined and standard conversions) involved on the two candidates and why one is not better than the other.
Note: if operator double() is changed to operator bool(), all three (clang, vc, gcc) will refuse to compile with similar ambiguous error.
It should be easier to picture why the overload resolution is ambiguous by going through it step-by-step.
§13.5.5 [over.sub]
Thus, a subscripting expression x[y] is interpreted as x.operator[](y) for a class object x of type T if T::operator[](T1) exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).
Now, we first need an overload set. That's constructed according to §13.3.1 and contains member aswell as non-member functions. See this answer of mine for a more detailed explanation.
§13.3.1 [over.match.funcs]
p2 The set of candidate functions can contain both member and non-member functions to be resolved against the same argument list. So that argument and parameter lists are comparable within this heterogeneous set, a member function is considered to have an extra parameter, called the implicit object parameter, which represents the object for which the member function has been called. [...]
p3 Similarly, when appropriate, the context can construct an argument list that contains an implied object argument to denote the object to be operated on.
// abstract overload set (return types omitted since irrelevant)
f1(Something&, foo const&); // linked to Something::operator[](foo const&)
f2(std::ptrdiff_t, char const*); // linked to operator[](std::ptrdiff_t, char const*)
f3(char const*, std::ptrdiff_t); // linked to operator[](char const*, std::ptrdiff_t)
Then, an argument list is constructed:
// abstract argument list
(Something&, char const[3]) // 'Something&' is the implied object argument
And then the argument list is tested against every member of the overload set:
f1 -> identity match on argument 1, conversion required for argument 2
f2 -> conversion required for argument 1, conversion required for argument 2 (decay)
f3 -> argument 1 incompatible, argument 2 incompatible, discarded
Then, since we found out that there are implicit conversions required, we take a look at §13.3.3 [over.match.best] p1:
Define ICSi(F) as follows:
if F is a static member function, [...]; otherwise,
let ICSi(F) denote the implicit conversion sequence that converts the i-th argument in the list to the type of the i-th parameter of viable function F. 13.3.3.1 defines the implicit conversion sequences and 13.3.3.2 defines what it means for one implicit conversion sequence to be a better conversion sequence or worse conversion sequence than another.
Now let's construct those implicit conversion sequences for f1 and f2 in the overload set (§13.3.3.1):
ICS1(f1): 'Something&' -> 'Someting&', standard conversion sequence
ICS2(f1): 'char const[3]' -> 'foo const&', user-defined conversion sequence
ICS1(f2): 'Something&' -> 'std::ptrdiff_t', user-defined conversion sequence
ICS2(f2): 'char const[3]' -> 'char const*', standard conversion sequence
§13.3.3.2 [over.ics.rank] p2
a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence.
So ICS1(f1) is better than ICS1(f2) and ICS2(f1) is worse than ICS2(f2).
Conversely, ICS1(f2) is worse than ICS1(f1) and ICS2(f2) is better than ICS2(f1).
§13.3.3 [over.match.best]
p1 (cont.) Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...]
p2 If there is exactly one viable function that is a better function than all other viable functions, then it is the one selected by overload resolution; otherwise the call is ill-formed.
Well, f*ck. :) As such, Clang is correct in rejecting that code.
It seems there is no question that both Something::operator[](const foo& f) and the built-in operator[](long, const char *) are viable candidate functions (13.3.2) for overload resolution. The types of real arguments are Something and const char*, and implicit conversion sequences (ICFs) I think are:
for Something::operator[](const foo& f): (1-1) identity conversion, and (1-2) foo("32") through foo::foo(const char*);
for operator[](long, const char *): (2-1) long(double(d)) through Something::operator double() const (inherited from Base), and (2-2) identity conversion.
Now if we rank these ICFs according to (13.3.3.2), we can see that (1-1) is a better conversion than (2-1), and (1-2) is a worse conversion than (2-2). According to the definition in (13.3.3),
a viable function F1 is defined to be a better function than another viable function
F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), ...
Therefore, neither of the considered two candidate functions is better than the other one, and thus the call is ill-formed. I.e. Clang appears to be correct, and the code should not compile.
It would seem from 13.6 in the C++11 spec that clang is correct here:
13.6
Built-in operators
[over.built]
The candidate operator functions that represent the built-in operators defined in Clause 5 are specified in
this subclause. These candidate functions participate in the operator overload resolution process as described
in 13.3.1.2 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 13.3.1.2, 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 5, 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 ]
:
For every cv-qualified or cv-unqualified object type T there exist candidate operator functions of the form
T& operator[](T *, std::ptrdiff_t);
T& operator[](std::ptrdiff_t, T *);
edit
Once you get past which operator functions exist, this just becomes standard overload resolution as described by section 13.3 of the standard -- about 10 pages of details, but the gist of it is that for a function call to not be ambiguous, there needs to be a single function that is at least as good a match as all the possible, viable functions on every argument, and a better match than the others on at least one argument. There's a lot of spec detail on exactly what 'better' means, but it boils down to (in this case) a match not requiring any user-defined conversion operator or object constructor is better than one which does.
So in this case, there are two viable matches:
void Something::operator[](const foo& f)
operator[](long, const char *)
The first is a better match for the first argument, while the second is a better match for the second. So unless there's some other function that is better than both of these, its ambiguous.
That latter point is a possble workaround -- add:
void operator[](const char *a) { return (*this)[foo(a)]; }
to class Something