![](/img/trans.png)
[英]Cannot convert unique_ptr<derived> to unique_ptr<base>
[英]How to convert unique_ptr<derived>* to unique_ptr<base>*?
我有 4 個類, base
, base_collection
和derived::base
, derived_collection::base_collection
;
在base_collection
中有一個帶有簽名的構造函數:
base_collection(unique_ptr<base> *begin, unique_ptr<base> *end)
在derived_collection
中有一個帶有簽名的構造函數:
derived_collection (unique_ptr<derived> *begin, unique_ptr<derived> *end)
顯然我想將它實現為
derived_collection (unique_ptr<derived> *begin, unique_ptr<derived> *end) :
base_collection(something(begin), something(end)) {}
但我正在為something
而苦苦掙扎。 我猜它是一個自定義迭代器,但到目前為止我的嘗試都失敗了,因為它一直告訴我我的自定義迭代器不能轉換為unique_ptr<base> *begin
。 在這一點上,我並沒有真正在意我正在做的事情是否是一個好主意,我只是很想知道如何讓它發揮作用。
我正在使用 C++17。
編輯
給出一些上下文unique_ptr<base> *base
是一個迭代器,不一定是指針。 base_collection
構造函數從begin
到end
迭代。
我想要做的是通過編譯器視為基本迭代器的開始/結束迭代器迭代派生集合。
something
就是這樣。 我不確定begin
和end
需要做什么才能使編譯器滿意。
更新
唉,沒有閱讀評論或不理解評論的人決定將它們全部隱藏,但似乎我試圖做的事情要么是不可能的,要么幾乎是不可能的,結論是需要一種不同的方法。
std::unique_ptr<Base>*
無法轉換std::unique_ptr<Derived>*
因為它們是不相關的類,即使模板參數Derived
公開派生自Base
。
要解決您的問題,您需要另一個級別的間接性。 例如,一種特殊的迭代器類型,它在Iter::operator*
和Iter::operator[]
中雙重取消引用unique_ptr<Base>*
並將Base&
向下轉換為Derived&
,並將Base*
* 向下轉換為Iter::operator->
中的Derived*
。 您可以從頭開始創建這樣的迭代器,但這需要大量的樣板代碼輸入,或者使用boost::iterator_facade
為您實現該樣板代碼。
因此,您將擁有Iter<Base, unique_ptr<Base>*>
和Iter<Derived, unique_ptr<Base>*>
並且它們必須可以相互轉換,只要第二個模板 arguments 匹配。 接着:
base_collection(Iter<Base, unique_ptr<Base>*> begin, Iter<Base, unique_ptr<Base>*> end);
derived_collection(Iter<Derived, unique_ptr<Base>*> begin, Iter<Derived, unique_ptr<Base>*> end) :
base_collection(begin, end) {} // Implicit conversion Iter<Derived, unique_ptr<Base>*> -> Iter<Base, unique_ptr<Base>*>.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.