Article View: comp.std.c++
Article #4018Re: Ambiguity when overloading operators
From: David Sachs
Date: Fri, 12 Apr 1996 20:17
Date: Fri, 12 Apr 1996 20:17
51 lines
2354 bytes
2354 bytes
Martin Aupperle <100754.2730@CompuServe.COM> writes:
>If I define
> struct X {
> X( int );
> operator const char* () const;
> /* other members */
> };
> X& operator + ( const X&, const X& );
>I cannot say
> X x1( 5 );
> X x2 = x1+3; // ambiguous
>Borland BC4.5 says that x1+3 is ambiguous. I know that it can
>1. convert 3 to an X and call operator + ( const X&, constX& )
>2. convert x1 to a const char* and do pointer arithmetics.
>Is the compiler right? I have in mind that a conversion towards a user defined
>type has precedence over the conversion to a fundamental type. So choice (1)
>should be right and it shoud not be ambiguous.
The compiler is right. The expression x1+3 is treated as if it were
a function call: operator+(x1,3). There are 2 relevant candidates.
1) operator+(const X&, const X&)
2) operator+(char* const, const int) (built-in pointer arithmetic)
The first form is a better match for the first argument. The second
for is a better match for the second argument. Therefore the construct
is ambiguous.
If you had an operator+(const X&, const int), it would be a best match
and would be used.
--
***** The stories about the first lady are hilarious. *****
David Sachs - Fermilab, HPPC MS369 - P. O. Box 500 - Batavia, IL 60510
Voice: 1 708 840 3942 Deparment Fax: 1 708 840 3785
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]
Technical Details
Message-ID:
<4kmd34$933@fsgi01.fnal.gov>Path:
arc1-ca.pugleaf.net!engnews1.Eng.Sun.COM!taumet!clamageReferences:
<960411233436_100754.2730_GHV68-1@CompuServe.COM>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews1.Eng.Sun.COM!taumet!clamage From: b91926@fsgi01.fnal.gov (David Sachs) Newsgroups: comp.std.c++ Subject: Re: Ambiguity when overloading operators Date: 12 Apr 1996 20:17:15 GMT Organization: FERMILAB, Batavia, IL Approved: clamage@eng.sun.com (comp.std.c++) Message-ID: <4kmd34$933@fsgi01.fnal.gov> References: <960411233436_100754.2730_GHV68-1@CompuServe.COM> Reply-To: sachs@fnal.fnal.gov NNTP-Posting-Host: taumet.eng.sun.com X-Newsreader: NN version 6.5.0 #9 (NOV) Content-Length: 1346 X-Lines: 44 Originator: clamage@taumet