2011-05-30 29 views
7

有很多類似這樣的SO問題,但我找不到我正在尋找什麼。如果這是重複的,我很抱歉。C++重載函數基於shared_ptr派生類

我有一個Parent類和兩個派生類,其從它繼承:

class Son : public Parent { ... }; 
class Daughter : public Parent { ... }; 

我然後聲明兩個shared_ptr基類,並用shared_ptr給每個派生類的實例化它們:

shared_ptr<Parent> son = shared_ptr<Son>(new Son()); 
shared_ptr<Parent> daughter = shared_ptr<Daughter>(new Daughter()); 

最後,我想有一個基於它指向哪個派生類來處理shared_ptr<Parent>的類。我可以用函數重載來實現這種效果的問題:

class Director { 
public: 
    void process(shared_ptr<Son> son); 
    void process(shared_ptr<Daughter> daughter); 
    ... 
}; 

所以我希望能夠編寫如下代碼:

shared_ptr<Parent> son = shared_ptr<Son>(new Son()); 
shared_ptr<Parent> daughter = shared_ptr<Daughter>(new Daughter()); 
Director director; 
director.process(son); 
director.process(daughter); 

現在,我不得不這樣做(這我想避免):

director.process_son(boost::shared_polymorphic_downcast<Son>(son)); 
director.process_daughter(boost::shared_polymorphic_downcast<Daughter>(daughter)); 

回答

7

這是不可能重載這樣,你需要一個switch語句對Director一個方法中實現與派遣類似的東西。

也許你應該移動process()方法將Parent類(和SonDaughter覆蓋它),這樣你可以使用正常的虛擬函數解析調用正確的。

3

我不確定是否有更好的方法,所以我通常在這種需求上使用訪客模式http://en.wikipedia.org/wiki/Visitor_pattern或類似的雙調度技巧。

您的對象可能不知道shared_ptr自己,但通常簡單的引用工作得很好。

0

理想情況下,Parent將提供足夠豐富的界面,以便Director正確處理每個孩子,而不需要知道孩子是哪個孩子。

class Director { 
public: 
    void process(shared_ptr<Parent> obj); 
}; 

如果由於某些原因無法實現此功能,則有許多設計選項。如上所述,您可以將流程與子類連接在一起。如果不能滿足您的需求就可以了,例如,從導演隔離過程:

class ProcessSon: public Process, private Son { 
public: 
    void SpecificProc1(shared_ptr<Parent> obj) { 
    // Make this part of the process based on class Son 
    } 

    void SpecificProc2(shared_ptr<Parent> obj) { 
    // Make this part of the process based on class Son 
    } 
    ... 
}; 

Daughter一個類似與指針一起發送相應Process到類的process方法Director