Re: [cpp] 派生类成员函数指针->基类成员函数指针->派生类成员函数指针,这个转换过程是否安全?

analyst qiaojie at gmail.com
Wed Apr 19 11:05:30 CST 2006


这段代码显然是思维混乱,在一个迷宫里走的太远,忘记了自己从哪里来,要往何处去。


在06-4-18,jiyong wu <jiyong.wu at gmail.com> 写道:
>
> 最近想到一个技巧,涉及基类和派生类成员指针的互相强制类型转换过程,不敢确认是否存在问题,所以想借助大家的法眼了。
>
> 派生类成员函数指针->基类成员函数指针->派生类成员函数指针,这个转换过程是否安全?
>
> 例子虽然简化了,还稍有复杂:
>
>
> class Base
> {
>     typedef void (Base::*MemFunSav)();
>
>     MemFunSav mfsav;
>     void (Base::*invoker)();
>
> public:
>     virtual ~Base() {}
>
>     virtual void run() = 0;
>
>     template <typename T>
>     void do_something( void (T::*on_done_callback)() )
>     {
>         invoker = &Base::invoke<T>;
>         mfsav = static_cast<MemFunSav>(on_done_callback);
>         // ...
>         // do/wait something done
>     }
>
> public: // simple
>     void on_time_to_callback()
>     {
>         (this->*invoker)();
>     }
>
> private:
>     template <typename T>
>     void invoke()
>     {
>         typedef void (T::*Cb_MemF)();
>
>         T* inst = static_cast<T*>(this);
>         Cb_MemF mf = static_cast<Cb_MemF>(mfsav);
>         (inst->*mf)();
>     }
> };
>
> struct Derived : public Base
> {
>     virtual void run()
>     {
>         // ....
>         do_something( &Derived::wake_up );
>     }
>
>     void wake_up()
>     {
>         // hello world
>     }
> };
>
> Base* foo__;
>
> void foo()
> {
>     foo__->on_time_to_callback();
> }
>
> int main()
> {
>     Derived* inst = new Derived;
>
>     foo__ = inst;
>
>     inst->run();
>
>     // ...........
>     // later, somewhere
>     foo();
> }
>
> ~
>
>
>
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codingnow.com/pipermail/cpp/attachments/20060419/f475d4c2/attachment.html


More information about the Cpp mailing list