I've browsed through a lot of questions related to conversion, but it seemed none of them discussing about explicit keyword in this way. Here's the code:
struct B;
struct A{
/*explicit*/ A(const B&){ cout << 1; } // *1
};
struct B{
/*explicit*/ operator A()const{ cout << 2; } // *2
};
void foo(const A &){}
int main(void){
B b;
foo( /*static_cast<A>*/ (b) ); // *3
}
Result: (Y: uncommented, N:commented, X: either)
# | *1 | *2 | *3 |output|
1 | N | N | N |error |
2 | N | N | Y | 1 |
3 | N | Y | N | 1 |
4 | N | Y | Y | 1 |
5 | Y | N | N | 2 |
6 | Y | N | Y | 1 |
7 | Y | Y | N |error |
8 | Y | Y | Y | 1 |
1, 7 are errors, which is normal.(ambiguous and no auto conversion)
2 seems that constructor have higher precedence, but why?
3, 5 are easy to understand.
4 is weird since it doesn't call the explicit one. why?
6 may be due to 'explicit' or constructor having higher precedence. Which one is the reason?
8 seems that constructor have higher precedence, but why?
Could someone offer some explanations? Thanks!