For two unrelated classes "class A" and "class B" and a function
B convert(const A&);
Is there a way to tell C++ to automatically, for any function that takes "class B" as argument, to auto convert a "class A".
Thanks!
What you would normally do in this case is give B
a constructor that takes an 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 B
can be constructed from an A
".
Another method is to use a conversion operator:
class A
{
public:
operator B(void) const;
}
And the compiler will say "How can I make A
a B
? Oh, I see A
can be converted to B
".
Keep in mind these are very easy to abuse. Make sure it really makes sense for these two types to implicitly convert to each other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With