You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

70 lines
2.0 KiB

/**
* Copyright (c) 2018 Niklas Rosenstein
* MIT licensed.
*
* @description A very simple implementation of a view on an STL container.
*/
#pragma once
#include <cassert>
namespace niklasrosenstein {
/* A view for a range of elements in a container. */
template <class C>
class span {
public:
typedef typename C::value_type value_type;
typedef typename C::size_type size_type;
typedef typename C::iterator iterator;
typedef typename C::const_iterator const_iterator;
inline span(C& container)
: container(container), start(0), max(container.size()) { }
inline span(C& container, size_type start, size_type max)
: container(container), start(start), max(max)
{
assert(start >= 0 && start <= container.size());
assert(max >= start && max <= container.size());
}
inline iterator begin() { return this->container.begin() + this->start; }
inline iterator end() { return this->container.begin() + this->max; }
inline value_type const& operator [] (size_type index) const {
assert(index >= 0 && (this->start + index) < this->max);
return this->container[this->start + index];
}
inline value_type& operator [] (size_type index) {
return const_cast<value_type&>(static_cast<span const*>(this)->operator [] (index));
}
inline size_type size() const { return (this->max - this->start); }
private:
template <typename L>
friend span<L> make_span(span<L>&, typename L::size_type, typename L::size_type);
C& container;
size_type start, max;
};
template <typename C>
span<C> make_span(C& container) {
return span<C>(container);
}
template <typename C>
span<C> make_span(C& container, typename C::size_type start, typename C::size_type max) {
return span<C>(container, start, max);
}
template <typename C>
span<C> make_span(span<C>& aspan, typename C::size_type start, typename C::size_type max) {
return span<C>(aspan.container, start + aspan.start, max + aspan.start);
}
} // namespace niklasrosenstein