簡體   English   中英

矢量的隱式轉換 <shared_ptr<Foo> &gt;向量 <shared_ptr<const Foo> &gt;

[英]Implicit conversion of vector<shared_ptr<Foo> > to vector<shared_ptr<const Foo> >

根據此頁面,您可以隱式地將shared_ptr<Foo>轉換為shared_ptr<const Foo> 這很有道理。

但是,當我嘗試將包含shared_ptr<Foo>std::vector轉換為包含shared_ptr<const Foo>std::vector時,我遇到了錯誤。

有沒有一種很好的方法來實現這種轉換?

否: std::vector<shared_ptr<Foo> >std::vector<shared_ptr<const Foo> >是不同的類型,因此您不能將one的對象視為另一種類型的對象。

如果你真的需要一個std::vector<shared_ptr<const Foo> > ,你可以輕松地創建一個shared_ptr與原始元素相同的元素:

std::vector<shared_ptr<Foo> > v;
std::vector<shared_ptr<const Foo> > cv(v.begin(), v.end());

但是,如果您根據迭代器編寫代碼,則不應該有任何問題。 也就是說,而不是使用

void f(const std::vector<shared_ptr<const Foo> >&);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v);

你應該使用

template <typename ForwardIterator>
void f(ForwardIterator first, ForwardIterator last);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v.begin(), v.end());

這樣,函數f只需要它獲得一系列可用作const Foo指針的東西(或者如果函數假定范圍包含shared_ptr ,則為shared_ptr<const Foo> s)。

當函數使用范圍而不是容器時,您將函數與基礎數據分離:它不再重要,數據實際是什么或如何存儲,只要您可以以您需要使用的方式使用它它。

vector<TYPE>vector<const TYPE>是兩種不同的類型。 所以沒有hack或臟代碼就不可能

為什么需要std::vector<shared_ptr<Foo const> > 轉換很容易; 只需使用std::vector的兩個迭代器構造函數。 但在許多情況下,您不需要它:通常,const-correctness與動態分配的對象無關,如果您需要shared_ptr<Foo const> ,則從向量中提取對象時會有自動轉換。

暫無
暫無

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

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