Two phase implicit casting in c++

折月煮酒 提交于 2019-12-11 20:28:26

问题


Isn't there something in the c++ standard that states I can implicitly cast two time? i.e. in case my function takes object A and I call it with object C I wont get compilation error even if there is no direct cast between C and A but there is a cast from C to B and from B to A? At some point in life I though this code was legal but today I found out I was wrong.

class A {};

class B {
  A m_a;
public:
  operator A () { return m_a; }
};

class C {
  B m_b;
public:
  operator B () { return m_b; }
};


void f(A a){}

int main()
{
  C c;
  f(c);
  return 0;
}

回答1:


An implicit conversion can only involve a single user-defined conversion. It can also contain built-in conversions (such as int to long) before and/or after the user-defined conversion.

Your code is not valid since it would require two user-defined conversions, C to B to A (assuming that you meant to say operator A not operator int in B). There's a good reason for this: to allow two conversions, the compiler would have to try every possible intermediate type, and there are an infinite number of possible types.

By the way, there are no casts involved here. A cast is an explicit type conversion.




回答2:


Since you want to convert C to A, the conversion operator actually needs to be A, not B. You get a B, but it doesn't turn into an A without casting. However, returning B as an A will do an implicit conversion.

class C {
  B m_b;
public:
  operator A () { return m_b; }
};

Live example



来源:https://stackoverflow.com/questions/20102431/two-phase-implicit-casting-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!