Prev: Why does std::basic_ios overload the unary negation operator?
Next: Current time based on a timezone?
From: Jeffrey Schwab on 16 Jul 2010 01:19 On 7/15/10 7:46 PM, Seungbeom Kim wrote: > struct A > { > A(int); > friend A operator+(const A&, int); > A operator+(const A&); > }; > > int main() > { > A(1)+2; > } > > Comeau C++ gives an error for this: > > error: more than one operator "+" matches these operands: > function "operator+(const A&, int)" > function "A::operator+(const A&)" > operand types are: A + int > A(1)+3; > ^ GCC agrees with Comeau about the error, but accepts the code if A is passed by value in the friend operator: friend A operator+(A, int); Apparently, binding A(1) to the reference-type parameter counts as an implicit conversion for purposes of overload resolution, at least as implemented by GCC. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Francis Glassborow on 16 Jul 2010 01:32 Seungbeom Kim wrote: > On 2010-07-13 19:48, Pete Becker wrote: >> Off hand, it looks like ob1 + ob2 is returning a Test object, and since >> operator+ takes a non-const Test object, it can't be called with a >> temporary. Both free functions should take their Test object by const >> reference or by value, and the member operator+ should be marked const. > > I found something interesting when the member operator+ is not const. > A minimal example: > > struct A > { > A(int); > friend A operator+(const A&, int); > A operator+(const A&); > }; > > int main() > { > A(1)+2; > } > > Comeau C++ gives an error for this: > > error: more than one operator "+" matches these operands: > function "operator+(const A &, int)" > function "A::operator+(const A &)" > operand types are: A + int > A(1)+3; > ^ > No you are missing the point. Neither of your operator+ functions is an exact match. the friend version matches on the second parameter but needs the first one to be promoted from 'A' to 'A const' (the restriction on using temporaries as arguments does not change the basic type of the temporary). The member function requires a conversion from int to A. The best match rules do not help because they do not apply when the mismatches are on different parameters. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
First
|
Prev
|
Pages: 1 2 Prev: Why does std::basic_ios overload the unary negation operator? Next: Current time based on a timezone? |