问题描述
建议调用者使用const_iterator模板参数创建非const iterator_range以证明迭代对象具有足够的生命周期。
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?
特别是,我如何实现const-这段代码的正确性?
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);
推荐答案
在范围内使用非const引用 避免绑定到临时工具¹
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));
¹标准C ++延长了绑定到const的临时生命周期-reference变量,但这不适用于绑定到对象成员的引用。因此,通过引用汇总范围很容易出现这种错误。
¹ 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甚至 注意事项/检查一些Boost Range功能(像适配器一样,使用起来经常太不安全;我经常陷入这些陷阱,而不是承认。
/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.
²除了
这篇关于如何创建const boost :: iterator_range的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!