【问题标题】:How do I create a const boost::iterator_range如何创建 const boost::iterator_range
【发布时间】:2016-07-21 18:52:17
【问题描述】:

Why does boost::find_first take a non-const reference to its input? 处的评论建议“调用者使用 const_iterator 模板参数创建非 const iterator_range 以“证明”迭代对象具有足够的生命周期。”

这是什么意思,我该怎么做?

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

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

【问题讨论】:

标签: c++ boost iterator constants const-iterator


【解决方案1】:

拥有对范围的非常量引用可以避免绑定到临时对象¹

我会通过让编译器完成你的工作来避免你的难题²:

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

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

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

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

² 除了您提供的样本中的we cannot reproduce it

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2018-09-10
    • 2012-06-24
    • 2012-10-29
    • 2012-10-28
    • 1970-01-01
    • 2016-12-17
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多