Hello,
I have a particular set up of cast operators and constructors which is leading to a compile-time ambiguity error. I am wondering if somebody can explain why this is happening and what can be done to fix it.
For example, here we have 2 classes:
class A
{
int val;
public:
A(){val=0;}
A(const A& o){val=o.val;}
A(int i){val=i;}
A&operator=(const A&o){val=o.val;return *this;}
A&operator=(int i){val=i;return *this;}
operator int(){return val;}
};
class B
{
int val;
public:
B(int i){val=i;}
operator A(){return A(val);}
operator double(){return 0.0;}
};
They work fine but don't really do anything at all. The purpose of the A operator in B is to allow such constructs as a=(A)b
. However when I try to compile this:
A a;
B b(7);
a=(A)b;
or even this:
A a;
B b(7);
a=b;
I get a compiler error telling me that there is an ambiguous call. I can understand which functions are being called ambiguously, but I would have thought that conversion would only go one level deep (b becomes type A, gets copied to a) why would the compiler even try the implicit int conversion on the A version of b? or the conversion path of B->double->int->A?