Reputation: 16640
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
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
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
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
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