2015-05-21 51 views
0

所以我有這樣的:模板是最佳選擇嗎?如果是這樣,這是正確的語法?

//base class 
class InterfaceItem 
{ 
public: 
    //iterates through m_SubItems vector looking for an item with that name and 
    //returns it 
    InterfaceItem* GetSubItem(string Name); 

private: 
    vector<InterfaceItem*> m_SubItems; 
} 

//one of the classes that derive from InterfaceItem 
class Window : public InterfaceItem 
{ 
    //other functions 
} 

所以,如果我這樣做

Window ThisWindow; //pretend it is already initialized and has sub-items 
ThisWindow.GetSubItems(); 

它會返回一個類型InterfaceItem *的對象,所以我不能夠訪問任何的窗口特定功能除非我做類似的東西

Window* TempWindow = static_cast<Window*>(ThisWindow.GetSubItems()); 

什麼是最好的解決方案呢?它是使用函數模板嗎?如果是這樣,這是否是正確的語法?

class InterfaceItem 
{ 
public: 
    template<class Type*> Type* GetSubItem(string Name); 

private: 
    vector<InterfaceItem*> m_SubItems; 
} 

我試過這個,我得到了一些WEIRD錯誤。與此無關的文件開始說,清楚包含#的類不存在,並且其他一些奇怪的東西

回答

0

在主叫端使用static_cast實際上是一個好方法。您需要在某處撥打static_cast。如果您不在接收方撥打電話,您需要在GetSubItem內撥打電話。

更好的方法是,如果您啓用了RTTI並且可以犧牲一點性能,那麼應該使用dynamic_cast來代替。區別在於dynamic_cast只有在subItem指向的值實際上是Window類型的實例時纔會成功,否則將返回nullptr。這樣你可以寫:

Window* TempWindow = dynamic_cast<Window*>(ThisWindow.GetSubItems()); 
if (nullptr != TempWindow) { 
    // process the window 
} 
else { // that particular subitem is not a Window* 
    // handle failure somehow 
} 
+0

非常感謝你的回答!最後我設法使用了模板函數。我發現我得到那些荒謬奇怪的錯誤的原因是因爲我使用了這種語法,其中「*」沒有意義。我只是刪除了那部分,並且它在我改變呼叫之後正確地編譯了,我想「(...) - >模板GetSub (」要查找的名稱「)(其餘代碼)」。 –