"balor" <ur*@4refs.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com
I have a class with a casting operator but GCC doesn't want to cast as
necessary and I'm wondering if this is legal or not.
class A {
public:
void test() {}
};
class Wrapper {
public:
Wrapper(A a) : a(a) {}
operator A &() { return a; }
private:
A a;
};
int main() {
A a;
Wrapper wrapper(a);
((A &)wrapper).test(); // works
wrapper.test(); // compile error
return 0;
}
Anyone have any idea whats wrong with wrapper.test()? The compiler
should be able to tell that if it casts to (A &), then a test() method
exists.
It doesn't work like that. For it to compile, the compiler would need to
iterate through the conversion operators and then see if there is a test()
function for any of the possible conversions. Apart from the fact that it is
a lot of work for the compiler, there is a high risk that it could lead to
erroneous code compiling. The compiler needs a reason to believe that you
really wanted an A reference where you wrote a Wrapper object. The usual
reason is that you supplied a Wrapper object as an argument of a function
that takes an A object. Given
void foo(A& a)
{
a.test();
}
foo(wrapper);
will compile. You have already identified one alternative in the form of a
cast. "BigBrian" has given another.
--
John Carson