std::vector
和几乎所有其他容器都有一种非常方便的边界检查方法:at()
。 std::span
显然没有这个功能。
之外
很笨重,但像这样:
template<class Container>
auto& at(Container&& c, std::size_t pos){
if(pos >= c.size())
throw std::out_of_range("out of bounds");
return c[pos];
}
template<class Iterator, class Container>
auto& at(Container&& c, Iterator&& it){
if(std::distance(c.begin(), it) >= c.size())
throw std::out_of_range("out of bounds");
return *it;
}
将span引入标准库的论文说:
范围检查和边界安全
对跨域封装的数据的所有访问都在概念上进行范围检查,以确保它们保持在跨域的界限内。 当运行时未能满足SPAN的边界安全约束时,实际发生的是未定义的行为。
也就是说,操作具有狭义的契约,给了实现者自由。
如果您的标准库不允许您将行为控制到适当的粒度。 gsl-lite提供了可配置的合同违反行为的插入替换。 Microsoft GSL以前是可配置的,但现在总是在合同违反时终止,这里讨论(这可能是您想要的)。