How do I create a const boost::iterator_range

和自甴很熟 提交于 2019-12-10 10:27:42

问题


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:


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



来源:https://stackoverflow.com/questions/36365241/how-do-i-create-a-const-boostiterator-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!