
Why is casting required here?
On Mon, 9 Sep 2002 21:11:03 -0500, "John Keenan"
Quote:
>The following snippet of code:
> class base{};
> class derived : public base{};
> class container{
> private:
> derived* derived__;
> public:
> derived& element();
> };
> derived&
> container::element()
> {
> return *derived__;
> }
> base& ( container::* method ) ( void ) = container::element;
>generates the following error on the last line:
> error C2440: 'initializing' : cannot convert from
> 'class derived &(__thiscall container::*)(void)' to
> 'class base &(__thiscall container::*)(void)'
>It appears to me that there is sufficient information available for this to
>work. Is there an explanation why this error is generated? Is there a better
>way to make this work than to use a cast? (MS VC++ 6 SP3)
Using the cast gives undefined behaviour. Basically, the only
conversion allowed for member function pointers is:
T (Base::*)(params) to T (Derived::*)(params)
The cast you are doing is changing the return type of the function,
and therefore can't work.
Rather than mess around with function pointers, consider using a
callback library like boost.function. See www.boost.org
Tom