C ++ 11: Ambiguity between constructor conversion and conversion function when initializing Pass-By-Value parameter?

#include <iostream> using namespace std; struct Y; struct X { X(const Y&) { cout << "converting constructor" << endl; } }; struct Y { operator X() { cout << "conversion function" << endl; } }; void f(X x) {} int main() { Y y; f(y); } 

In the conversion function above, the conversion constructor is assigned by my compiler (gcc 4.6.1), however in the standard it states that: p>

Custom conversions apply only where they are explicit

It would seem that in this case there is ambiguity. Can someone explain the contradiction?

I would expect the above to not compile. I'm also sure that a few years ago, Scott Meyers wrote about this particular example and said that it would not compile. What am I missing?

+6
c ++ copy-constructor language-lawyer c ++ 11 implicit-conversion
source share
2 answers

Since constructor X wants a const argument, it prefers an operator. If you remove const in constructor X, the compiler complains about ambiguity. If there is more than one function with reference parameters, it is preferable that one with the most relaxed qualifications.

Good answer here

+5
source share

There is no ambiguity, the only valid conversion is provided by the conversion function.
Note that y not const ; your transform constructor needs a const argument.

It would be ambiguous if your conversion constructor accepted a non-const reference.

Online example:

 #include <iostream> using namespace std; struct Y; struct X { X(Y&) { cout << "converting constructor" << endl; } }; struct Y { operator X() { cout << "conversion function" << endl; } }; void f(X x) {} int main() { Y y; f(y); return 0; } 

Output:

prog.cpp: in member function Y: operator X ():
prog.cpp: 13: warning: no return in function returning non-void
prog.cpp: In the function 'int main ():
prog.cpp: 21: error: conversion from "Y to" X is ambiguous
prog.cpp: 13: note: candidates: Y :: operator X ()
prog.cpp: 8: note: X :: X (Y &)

+1
source share

All Articles