Search code examples
c++type-conversionoverload-resolution

Overload resolution and user-defined conversion


Consider this example:

struct Foo
{
    Foo(int){cout << "Foo(int)\n";}
    Foo(double){cout << "Foo(double)\n";}

    operator int()const{cout << "operator int()\n"; return 0;}
    operator double()const{cout << "operator double()\n"; return 0.;}
};

void bar(Foo){cout << "bar(Foo)\n";}
void bar(float){cout << "bar(float)\n";}



int main()
{

    int i = 5;
    bar(i); // whey bar(float) and not bar(Foo)?
}
  • I know I shouldn't overload the "converting-ctor" to take relate types (here arithmetic types) but just for understanding better function matching and user-defined-conversion.

  • Why the call to bar is resolved to bar(float) and not bar(Foo) as long as Foo has an exact match for this argument (int)?

  • Does it mean that standard conversion is preferred over user-defined conversion?


Solution

  • Does it mean that standard conversion is preferred over user-defined conversion?

    Yes. Standard conversions are always preferred over user-defined ones. See this

    In deciding on the best match, the compiler works on a rating system for the way the types passed in the call and the competing parameter lists match up. In decreasing order of goodness of match:

    • An exact match, e.g. argument is a double and parameter is a double
    • A promotion
    • A standard type conversion
    • A constructor or user-defined type conversion