Notinlist
Notinlist

Reputation: 16640

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 which should work:

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

Upvotes: 1

Views: 359

Answers (5)

Bids
Bids

Reputation: 2449

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 );
}

Upvotes: 0

anon
anon

Reputation:

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.

Upvotes: 2

neuro
neuro

Reputation: 15180

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

Upvotes: 2

mukeshkumar
mukeshkumar

Reputation: 2778

Not possible without altering class definition

Upvotes: 0

sbi
sbi

Reputation: 224039

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.)

Upvotes: 0

Related Questions