问题描述
我有这样的类:
class RPNExpr
{
std::vector<std::unique_ptr<Expr> > m_exprs;
};
m_exprs的每个元素都是由构建器函数进行堆分配的,应该可以被其他类读取,但是是完全由RPNExpr拥有的,并且当RPNExpr超出范围时应该被销毁。
Each element of m_exprs is heap-allocated by a builder function, should be readable by other classes, but is purely owned by RPNExpr and should be destructed when the RPNExpr goes out of scope.
对于m_exprs的读者来说,能够通过const获得一个迭代器将是很好的Expr& ;即,隐藏向量持有unique_ptrs的事实的迭代器。我想这是为了与其他类的一致性,其中保存unique_ptrs到他们的数据和返回const T&
It would be nice for readers of m_exprs to be able to get an iterator over const Expr&, i.e. an iterator which hides the fact that the vector is holding unique_ptrs. I would like this for the sake of consistency with other classes, which hold unique_ptrs to their data and return const T& to them.
这个界面可能类似:
class RPNExpr
{
public:
SomeIterator expr_begin();
SomeIterator expr_end();
private:
std::vector<std::unique_ptr<Expr> > m_exprs;
};
然后,消费者应该能够使用标准的迭代器运算符来迭代Exprs。
Consumers should then be able to iterate over the Exprs by using standard iterator operators.
有很好的方法吗?我应该编写一个向量包装器抽象指针吗?我应该不是这样做和使用除了unique_ptrs之外的东西在我的矢量?
Is there a nice way to do this? Should I be writing a vector wrapper which abstracts over the pointers? Should I not be doing this at all and use something other than unique_ptrs in my vector?
推荐答案
boost中有一个迭代器适配器只是:
There's an iterator adaptor in boost that does just that:
#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; }
这篇关于在const T& in std :: vector< std :: unique_ptr< T> >的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!