2009-02-01 146 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 *細節對於你的類的用戶是隱藏的,這很好。