问题
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