Following is the test code:
struct A
{
operator int ();
operator int () const;
};
void foo (const int);
Now, upon invoking:
foo(A()); // calls A::operator int()
Why does it always chooses the non-const version ? Even making operator const int () const; doesn’t have any effect on invoking foo(). Apart from standard reference, can someone explain logically, the reason behind it ?
A()gives you a temporaryAobject that is not const-qualified. TheA()expression is an rvalue expression, yes, but that does not make theAobject const-qualified.Since the
Aobject is not const-qualified, the non-constoperator int()is an exact match and the constoperator int()requires a qualification conversion, so the non-const overload is selected as the best match.If you want it to be const-qualified, you’d need to explicitly request a const-qualified
A:where
identityis defined asNote that there is really no difference between
operator const int() constandoperator int() const: the result is an rvalue and only class-type rvalues can be const-qualified (intis not a class type).Note also that there is no difference between the
void foo(const int)that you have andvoid foo(int). Top-level const-qualifiers on parameter types do not affect the type of the function (i.e., the type of both of those declarations isvoid foo(int)). Among other reasons, this is because it doesn’t matter to the caller whether there is a top-level const-qualifier; it has to make a copy regardless. The top-level const-qualifier affects only the definition of the function.