如何创建const boost::iterator_range

How do I create a const boost::iterator_range

本文关键字:boost iterator range const 何创建 创建      更新时间:2023-10-16

为什么boost::find_first对其输入进行非常量引用?建议"调用者使用const_iterator模板参数创建一个非常量迭代器_range,以"证明"迭代对象有足够的生存期。"

这意味着什么?我该怎么做?

特别是,如何使用此代码实现常量正确性?

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

对范围进行非常量引用可避免绑定到临时性

我会让编译器做你的工作来避免你的难题²:

tMyMap const& my_map; // NOTE const
// ...
return boost::make_iterator_range(my_map.lower_bound(123), mymap.upper_bound(456));

标准C++延长了绑定到常量引用变量的临时变量的生存期,但这不适用于绑定到对象成员的引用。因此,通过引用聚合范围很容易出现这种错误。

/OT:IMO甚至的预防措施/检查一些Boost Range功能(如适配器)通常太不安全,无法使用;我陷入这些陷阱的次数比我愿意承认的要多。

²除了我们无法从您提供的样本中复制之外