How do I create a const boost::iterator_range

2019-05-10 09:20发布

The comment at Why does boost::find_first take a non-const reference to its input? suggests "the caller to create a non-const iterator_range with const_iterator template parameter to "prove" that the iterated object has a sufficient lifetime."

What does this mean and how do I do it?

In particular, how do I achieve const-correctness with this code?

typedef std::map<int, double> tMyMap;
tMyMap::const_iterator subrange_begin = my_map.lower_bound(123);
tMyMap::const_iterator subrange_end = my_map.upper_bound(456);

// I'd like to return a subrange that can't modify my_map
// but this vomits template errors complaining about const_iterators
return boost::iterator_range<tMyMap::const_iterator>(subrange_begin, subrange_end);  

1条回答
太酷不给撩
2楼-- · 2019-05-10 09:36

Having non-const references to the range avoids binding to temporaries ¹

I'd avoid your conundrum² by letting the compiler do your work:

tMyMap const& my_map; // NOTE const
// ...

return boost::make_iterator_range(my_map.lower_bound(123), mymap.upper_bound(456));

¹ Standard C++ extends lifetimes of temporaries bound to const-reference variables, but this doesn't apply to references bound to object members. Therefore, aggregating ranges by reference is very prone to this mistake.

/OT: IMO even with the precautions/checks some Boost Range features (like adaptors) are frequently too unsafe to use; I've fallen into those traps more often than I care to admit.

² apart from the fact that we cannot reproduce it from the sample you gave

查看更多
登录 后发表回答