Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous conversion to reference

Why is the conversion of CL instance to const int& ambiguous here?

struct CL
{
    operator const int&()
    {
    }
    operator int&()
    {
    }
};

void fnc(const int&)
{
}

int main()
{
    CL cl;
    fnc(cl);
}

There are two ways:
1). cl.operator const int&() leads to user-defined conversion
2). cl.operator int&() leads to user-defined conversion and then qualification conversion (int& to const int&)

First way is better than second way, isn't it? I saw Standard, but found nothing.

like image 818
Denis Avatar asked Sep 03 '14 11:09

Denis


People also ask

How do you fix an ambiguous error in C++?

You can resolve ambiguity by qualifying a member with its class name using the scope resolution ( :: ) operator. The statement dptr->j = 10 is ambiguous because the name j appears both in B1 and B2 .

What is ambiguous reference in C++?

Access to a base class member is ambiguous if you use a name or qualified name that does not refer to a unique function or object. The declaration of a member with an ambiguous name in a derived class is not an error. The ambiguity is only flagged as an error if you use the ambiguous member name.

How do you resolve ambiguity in inheritance?

Ambiguity in inheritance can be defined as when one class is derived for two or more base classes then there are chances that the base classes have functions with the same name. So it will confuse derived class to choose from similar name functions. To solve this ambiguity scope resolution operator is used “::”.

What is ambiguity error and how do you resolve it?

[‚am·bə′gyü·əd·ē ‚er·ər] (computer science) An error in reading a number represented in a digital display that can occur when this representation is changing; for example, the number 699 changing to 700 might be read as 799 because of imprecise synchronization in the changing of digits.


1 Answers

This is because both conversions are applicable (equally good) in this context. That is, both int& and const int& can be bound by const int&.

The conversion would not be ambiguous, if you had:

void fnc(int&)
{
}
like image 105
Piotr Skotnicki Avatar answered Sep 27 '22 16:09

Piotr Skotnicki