Ori*_*Ori 3 c++ polymorphism static-methods non-static
我有一个使用多态的奇怪问题.我有一个实现静态方法的基类.由于各种原因,此方法必须是静态的.基类还有一个纯虚方法run()
,由所有扩展类实现.我需要能够run()
从静态类调用.
当然,问题是静态类没有this指针.此方法可以在void*参数中传递.我一直试图想出一种聪明的方法将run方法传递给它,但到目前为止还没有任何工作.我也试过把它传递给它.这个问题是我必须实例化它,这需要知道扩展类.这破坏了多态性的整个目的.
关于如何解决这个问题的任何想法?
不要将它作为void*指针传递,将其作为指针(或引用)传递给基类:
class BaseClass
{
public:
static void something(BaseClass* self) { self->foo(); }
virtual void foo() = 0;
};
Run Code Online (Sandbox Code Playgroud)
当您必须通过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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
那会有帮助吗?
归档时间: |
|
查看次数: |
3254 次 |
最近记录: |