繁体   English   中英

c ++中具有多态性的静态方法

[英]static method with polymorphism in c++

我有一个使用多态的奇怪问题。 我有一个实现静态方法的基类。 由于各种原因,此方法必须是静态的。 基类还有一个纯虚方法run() ,它由所有扩展类实现。 我需要能够从静态类调用run()

当然,问题是静态类没有this指针。 此方法可以在void *参数中传递。 我一直试图想出一种聪明的方法将run方法传递给它,但到目前为止还没有任何工作。 我也试过把它传递给它。 这个问题是我必须实例化它,这需要知道扩展类。 这破坏了多态性的整个目的。

关于如何解决这个问题的任何想法?

不要将它作为void *指针传递,将其作为指针(或引用)传递给基类:

class BaseClass
{
public:
  static void something(BaseClass* self) { self->foo(); }
  virtual void foo() = 0;  
};

当您必须通过C API松散C ++对象时,通常会发生这种情况。 一个典型的例子是线程类。

这是执行此操作的标准习惯用语:

/** calls thread_func in a new thread passing it user_data as argument */
thrd_hdl_t c_api_thread_start(int (*thread_func)(void*), void* user_data);

/** abstract thread base class
* override my_thread::run to do work in another thread
*/
class my_thread {
  public:
    my_thread() hdl_(c_api_thread_start(my_thread::thread_runner,this)) {}
    // ...

  private:
    virtual int run() = 0; // we don't want this to be called from others

    thrd_hdl_t hdl_; // whatever the C threading API uses as a thread handle

    static int thread_runner(void* user_data)
    {
      my_thread* that = static_cast<my_thread*>(user_data);
      try {
        return that->run();
      } catch(...) {
        return oh_my_an_unknown_error;
      }
    }
};

那会有帮助吗?

为什么不传递对象的引用而不是方法,例如

static void func( BaseObject& o)
{
     o.run();
}

IMO,你最好的办法是摆脱静态方法。 找到解决方法你就是金色的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM