Iterating over const T& in a std::vector >

2019-07-23 04:51发布

问题:

I have a class like this:

class RPNExpr
{
    std::vector<std::unique_ptr<Expr> > m_exprs;
};

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.

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.

The interface for this might look something like:

class RPNExpr
{
public:
    SomeIterator expr_begin();
    SomeIterator expr_end();
private:
    std::vector<std::unique_ptr<Expr> > m_exprs;
};

Consumers should then be able to iterate over the Exprs by using standard iterator operators.

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?

回答1:

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

Source: http://www.boost.org/doc/libs/1_56_0/libs/iterator/doc/indirect_iterator.html