Static method with polymorphism in C ++

I have a weird problem using polymorphism. I have a base class that implements a static method. This method must be static for various reasons. The base class also has a pure virtual method run()that is implemented by all extended classes. I need to be able to call run()from a static class.

The problem, of course, is that the static class does not have this pointer. This method can be passed in the void * parameter. I tried to come up with a smart way to pass the run method into it, but so far nothing has worked. also tried to pass it into it. The problem is that I would have to create it, which requires knowledge of the extended class. This defeats the whole goal of polymorphism.

Any ideas on how to do this?

+3
source share
4 answers

Do not pass it as a void * pointer, pass it as a pointer (or link) to the base class:

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

This usually happens when you need to squirrel your C ++ objects through the C API. A classic example is the thread class.

Here's the standard idiom for this:

/** 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;
      }
    }
};

Will this help?

+5
source

, , .

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

, . , .

+1

Source: https://habr.com/ru/post/1719732/


All Articles