C ++ Auto Conversions

For two unrelated classes, "class A" and "class B" and the function

B convert(const A&); 

Is there a way to say C ++ automatically, for any function that takes "class B" as an argument, to automatically convert "class A".

Thanks!

+7
c ++
source share
2 answers

What you usually did in this case is to give B constructor that takes A :

 class B { public: B(const A&); }; 

And do the conversion there. The compiler will say: "How can I make A a B ? Oh, I see that B can be built from A "

Another method is to use the conversion operator:

 class A { public: operator B(void) const; } 

And the compiler will say: "How can I do A a B ? Oh, I see that A can be converted to B "

Keep in mind that it is very easy to abuse. Make sure that it really makes sense for the two types to implicitly transform each other.

+10
source share

You can provide a translation operator or a one-parameter constructor.

+1
source share

All Articles