首页 > 解决方案 > 您如何使用标准跨度进行边界检查?

问题描述

std::vector几乎所有其他容器都有一种非常方便的边界检查方法:at(). std::span显然没有。

标签: c++c++20outofrangeexceptionstd-span

解决方案


相当笨重,但像这样:

  1. 使用位置
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];
}
  1. 使用迭代器:
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;
}

推荐阅读