views:

88

answers:

2

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!

+5  A: 

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.

GMan
I second the warning concerning implicit conversion operators. During the last ten years, whenever I was tempted to introduce such a thing (with the exception of a string class I once wrote), sooner or later it turned out to kick in when nobody expected it and was thus removed from the code - often at quite a cost. Also keep in mind that the compiler will always only ever invoke exactly _one_ user-defined conversion. So if there's also a user-defined conversion from `B` to `C`, you cannot call `void f(C)` with an `A`, because that would require two conversions.
sbi
+1  A: 

You can supply a cast operator, or a one-parameter constructor.

On Freund