[英]Iterating uniformly over std::vector<T> and std::vector<unique_ptr<T>>
[英]Iterating over const T& in a std::vector<std::unique_ptr<T> >
我有這樣的課:
class RPNExpr
{
std::vector<std::unique_ptr<Expr> > m_exprs;
};
m_exprs的每個元素都由構建器函數進行堆分配,應可由其他類讀取,但應完全由RPNExpr擁有,並且當RPNExpr超出范圍時應進行銷毀。
對於m_exprs的讀者來說,能夠在const Expr&上獲得一個迭代器將是一件好事,即,該迭代器隱藏了矢量持有unique_ptrs的事實。 我希望這樣做是為了與其他類保持一致,這些其他類將unique_ptrs保留在其數據中,並向它們返回const T&。
該界面可能類似於:
class RPNExpr
{
public:
SomeIterator expr_begin();
SomeIterator expr_end();
private:
std::vector<std::unique_ptr<Expr> > m_exprs;
};
然后,消費者應該能夠使用標准的迭代器運算符對Exprs進行迭代。
有沒有很好的方法可以做到這一點? 我應該編寫一個抽象指針的矢量包裝器嗎? 我是否應該完全不這樣做,而在向量中使用unique_ptrs以外的其他東西?
boost中有一個迭代器適配器,它可以做到這一點:
#include <boost/iterator/indirect_iterator.hpp>
...
using ExprIterator = boost::indirect_iterator<std::vector<std::unique_ptr<Expr>>::iterator>;
ExprIterator expr_begin() { return std::begin(m_exprs); }
ExprIterator expr_end() { return std::end(m_exprs; }
來源: http : //www.boost.org/doc/libs/1_56_0/libs/iterator/doc/indirect_iterator.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.