Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do bounds checking with std span?

std::vector and pretty much all other containers have a very convenient way of bounds checking: at(). std::span doesn't have that apparently.

  • Why?
  • Is there a replacement? Other than rolling out your own at()?
like image 649
Ayxan Haqverdili Avatar asked Aug 01 '26 05:08

Ayxan Haqverdili


1 Answers

Pretty clunky but something like this:

  1. using position
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. using iterators:
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;
}
like image 189
Alberto Sinigaglia Avatar answered Aug 02 '26 17:08

Alberto Sinigaglia