簡體   English   中英

C++ 重載一個 Function 基於 shared_ptr 派生的 Class

[英]C++ Overloading a Function Based on shared_ptr Derived Class

有很多與此類似的 SO 問題,但我無法准確找到我正在尋找的內容。 如果這是重復的,我很抱歉。

我有一個Parent class 和兩個繼承自它的派生類:

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

然后我向 Base class 聲明兩個shared_ptr ,並使用shared_ptr將它們實例化到每個派生類:

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

最后,我想要一個 class 根據它指向的派生類來處理shared_ptr<Parent> 我可以使用 function 重載來達到這個效果的問題是:

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));

不可能像那樣重載,您需要一個 switch 語句來在Director的一個方法中實現與調度類似的東西。

也許您應該將process()方法移動到Parent class (並在SonDaughter中覆蓋它),這樣您就可以使用普通的虛擬 function 分辨率來調用正確的分辨率。

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

您的對象可能自己不知道 shared_ptr,但通常簡單的引用就足夠了。

理想情況下, Parent會提供一個足夠豐富的接口,讓Director能夠正確處理每個孩子,而無需知道它是哪個孩子。

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

如果由於某種原因無法實現這一點,則有很多設計選擇。 如上所述,您可以將進程與子 class 鏈接在一起。 如果這不適合您的需求,例如,您可以將流程與主管隔離開來:

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連同指向 class 的指針一起發送到Directorprocess方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM