2015-10-12 37 views
0

大家好我有this的例子。通常在這種情況下,我會使用訪問者模式。但由於某種原因,寫了Base,DerivedA,0 DerivedB的人更喜歡dynamic_cast s。請記住,我無法更改Base,DerivedADerivedB類。 我有周圍的部分專業鑄造。請讓我知道這是一個好的解決方案還是有更好的解決方案?部分專業化建議

#include <iostream> 
using namespace std; 

class CBase{}; 

class CDerivedA: public CBase{}; 

class CDerivedB : public CBase{}; 

class CDerivedC : public CBase{}; 

template <typename T> 
void Draw(T* face) 
{ 
    cout<<"Base"<<endl; 
} 

template <> 
void Draw<>(CDerivedA* face) 
{ 
    cout<<"A"<<endl; 
} 

template <> 
void Draw<>(CDerivedB* face) 
{ 
    cout<<"B"<<endl; 
} 

int main() { 
    CDerivedA* a = new CDerivedA(); 
    CDerivedB* b = new CDerivedB(); 
    CDerivedC* c = new CDerivedC(); 

    Draw(a); 
    Draw(b); 
    Draw(c); 

    return 0; 
} 

回答

1

如果在編譯時已知類型,則可以簡單地使用函數重載。除了基類過載(或者需要的通用函數模板)之外,這也起作用。

void Draw(CBase* face); 
void Draw(CDerivedA* face); 
void Draw(CDerivedB* face); 

如果類型是在運行時已知的,你沒有選擇,修改類(即添加虛擬功能),你需要某種調度機制。不涉及許多類和樣板代碼的方法將是將類型映射到函數的表格,例如, std::map<std::type_index, std::function<void()>>或類似的。由於查找和動態調度開銷,可能效率不高。