c++ - Function Matching for parameters of type const T& and T -
i have question regarding c++ function matching parameters of types t
, const t&
. let's have following 2 functions:
void f(int i) {} void f(const int &ri) {}
if call f
argument of type const int
call of course ambiguous. why call of f
argument of type int
ambiguous? wouldn't first version of f
exact match , second 1 worse match, because int
argument must converted const int
?
const int ci = 0; int = 0; f(ci); // of course ambiguous f(i); // why ambiguous?
i know such kind of overloading doesn't make sense, because calls of f
ambiguous unless parameter type t doesn't have accessible copy constructor. i'm studying rules of function matching.
regards, kevin
edit: make question more clear. if have 2 functions:
void f(int *pi) {} void f(const int *pi) {}
then following call not ambiguous:
int = 0; f(&i); // not ambiguous, first version f(int*) chosen
although both versions of f
called &i
first version chosen, because second version of f
include conversion const.
is, first version "better match". in 2 functions:
void f(int i) {} , void f(const int &ri) {}
this additional conversion const
seems ignored reason. again both versions of f
called int
. again, second version of f
require conversion const
make worse match first version f(int).
int = 1; // f(int) requires no conversion // f(const int &) require const conversion // why both versions treated "equally good" matches? // isnt analogous f(int*) , f(const int*) example? f(i); // why ambiguous time?
one call involves "lvalue-to-rvalue conversion", other requires identity conversion (for references) or "qualification adjustment" (for pointers), , according standard these treated equally when comes overload resolution.
so, neither better on basis of differing conversions.
there is, however, special rule in standard, section 13.3.3.2, applies if both candidates being compared take parameter reference.
standard conversion sequence
s1
better conversion sequence standard conversion sequences2
if ...s1
,s2
reference bindings (8.5.3), , types references refer same type except top-level cv-qualifiers, , type reference initializeds2
refers more cv-qualified type reference initializeds1
refers.
there's identical rule pointers.
therefore compiler prefer
f(int*); f(int&);
over
f(const int*); f(const int&);
respectively, there's no preference f(int)
vs f(const int)
vs f(const int&)
, because lvalue-to-rvalue transformation , qualification adjustment both considered "exact match".
also relevant, section 13.3.3.1.4:
when parameter of reference type binds directly argument expression, implicit conversion sequence identity conversion, unless argument expression has type derived class of parameter type, in case implicit conversion sequence derived-to-base conversion.
Comments
Post a Comment