开发者

Implicit conversion between 3rd party types

There are two classes: A and B. There are algorithms for converting from type A to type B and back. We cannot touch the source code of them. Can I write an implicit conversion between the two types?

Example code whi开发者_如何学JAVAch should work:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return a;
}


No, I don't think so. Implicit conversion is usually coded with an overloaded operator. It is done for base types too. As you can't modify A and B code there is no way to tell the compiler how to do that. Your snippet will get an error.

You have to do explicit conversion. Just

return helper.convertToB(a);

my2c


No, but you can write a named free function to do it.

B ToB( const A & a ) {
   B b;
   // process a somehow to add its data  to b
   return b;
}

Your code then becomes:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return ToB( a );
}

which is arguably clearer than the implicit conversion would be.


There are two classes: A and B. There are algorithms for converting from type A to type B and back. We cannot touch the source code of them. Can I write an implicit conversion between the two types?

No, if A and B aren't related you can't. (And I am grateful for that. Implicit conversions give enough headaches as they are without the ability to create them for 3rd-party classes.)


Not possible without altering class definition


Even if you can't change the implementation of A or B, you could add an inline constructor to the definition of B that takes a const A&.

I would suspect however that unless the classes really are closely related it would be better to provide an explicit conversion function - implicit conversions can be a huge source of difficult-to-find bugs:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return ConvertAToB( a );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜