评论于为什么 boost::find_first 对它的输入采用非常量引用?建议“调用者使用 const_iterator 模板参数创建一个非常量 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);
有非常量引用到范围避免绑定到临时变量 1
我会通过让编译器完成您的工作来避免您的难题²:
tMyMap const& my_map; // NOTE const
// ...
return boost::make_iterator_range(my_map.lower_bound(123), mymap.upper_bound(456));
1 标准 C++ 延长了绑定到 const 引用变量的临时变量的生命周期,但这不适用于绑定到对象成员的引用。因此,通过引用聚合范围很容易出现此错误。
/OT:IMO 甚至with预防措施/检查 某些 Boost Range 功能(如适配器)通常使用起来太不安全;我陷入这些陷阱的次数比我愿意承认的还要多。
² 除了以下事实:我们无法复制它从你给出的样本来看
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)