2009-02-01 138 views
2

最近我一直在设计一个Thread类的库,我做了下面这样的主题抽象类:纯虚拟方法VS.函数指针

class Thread { 
public: 
    run() { /*start the thread*/ } 
    kill() { /*stop the thread*/ } 
protected: 
    virtual int doOperation(unsigned int, void *) = 0; 
}; 

房地产线程类将继承这个抽象类,并在其自己的逻辑实现doOperation方法,类似于Strategy Pattern

的问题是,我依靠它定义运行的线程在下面的函数是C后端库:

int startThread(char* name, (int)(*)(unsigned int, void*), int, int, int, void*); 

正如你所看到的;第二个参数是线程循环(主函数)的函数指针,这里是问题;由于我使用这个C函数来启动run方法中的线程,因此我将doOperation的地址传递给第二个参数,由于类型不匹配,无法完成此操作。

我试着用reinterpret_cast来返回一个指针,但是我ISO-C++禁止返回一个未初始化函数成员的指针。 我不知道如何克服这种冲突,使用静态方法是我猜想的唯一解决方案,但它炸毁了我的设计模式!

+0

Michael,Stefan,感谢您分享您的丰富想法,他们解决了我的问题。 – Josef 2009-02-02 00:29:58

+0

请参见下面的问题: - http://stackoverflow.com/questions/499153/passing-a-qualified-non-static-member-function-as-a-function-pointer/499299#499299 – 2009-02-01 08:59:45

回答

7

首先,请务必阅读Michael Burr提供的链接,因为它包含了很好的信息。于是,这里是C++ ISH伪代码吧:

int wrapperDoOperation(int v, void *ctx) 
{ 
    Thread *thread = (Thread *)ctx; 
    return thread->doOperation(v); 
} 

class Thread { 
public: 
    run() { 
     startThread("bla", wrapperDoOperation, bla, bla, bla, (void *)this); 
    } 
    kill() { /*stop the thread*/ } 
protected: 
    virtual int doOperation(unsigned int) = 0; 

friend wrapperDoOperation ......; 
}; 

的想法是,doOperation,作为主题的成员函数,不需要一个void *背景下,你可以只保留任何你作为对象本身的上下文传递。因此,您可以使用void指针将此指针传递给doOperation。注意void *细节对于你的类的用户是隐藏的,这很好。