template<class T>
struct array_view {
T* b = 0;
T* e = 0;
T* begin() const { return b; }
T* end() const { return e; }
std::size_t size() const { return end()-begin(); }
T& front() const { return *begin(); }
T& back() const { return *(end()-1); }
// basic constructors:
array_view(T* s, T* f):b(s), e(f) {}
array_view(T* s, std::size_t N):array_view(s, s+N) {}
// default ctors: (no need for move)
array_view()=default;
array_view(array_view const&)=default;
array_view& operator=(array_view const&)=default;
// advanced constructors:
template<class U>
using is_compatible = std::integral_constant<bool,
std::is_same<U, T*>{} || std::is_same<U, T const*>{} ||
std::is_same<U, T volatile*>{} || std::is_same<U, T volatile const*>{}
>;
// this one consumes containers with a compatible .data():
template<class C,
typename std::enable_if<is_compatible< decltype(std::declval<C&>().data()) >{}, int>::type = 0
>
array_view( C&& c ): array_view( c.data(), c.size() ) {}
// this one consumes compatible arrays:
template<class U, std::size_t N,
typename std::enable_if<is_compatible< U* >{}, int>::type = 0
>
array_view( U(&arr)[N] ):
array_view( arr, N )
{}
// create a modified view:
array_view without_front( std::size_t N = 1 ) const {
return {begin()+(std::min)(size(), N), end()};
}
array_view without_back( std::size_t N = 1 ) const {
return {begin(), end()-(std::min)(size(), N)};
}
array_view only_front( std::size_t N = 1 ) const {
return {begin(), begin()+(std::min)(size(), N)};
}
array_view only_back( std::size_t N = 1 ) const {
return {end()-(std::min)(size(), N), end()};
}
};
Now some functions that let you easily create it:
template<class T, std::size_t N>
array_view<T> array_view_of( T(&arr)[N] ) {
return arr;
}
template<class C,
class Data = decltype( std::declval<C&>().data() ),
class T = typename std::remove_pointer<Data>::type
>
array_view<T> array_view_of( C&& c ) {
return std::forward<C>(c);
}
template<class T>
array_view<T> array_view_of( T* s, std::size_t N ) {
return {s, N};
}
template<class T>
array_view<T> array_view_of( T* s, T* e ) {
return {s, e};
}
and we are done the boilerplate part.
for (auto & b : bus) {
for (auto & p : bus.port) {
for (auto & d : array_view_of(bus.data).only_front(4)) {
store_the_address_of_d_for_use_elsewhere(d);
}
}
}
live example
Now I would only advocate this approach because array_view
is shockingly useful in many different applications. Writing it just for this case is silly.
Note that the above array_view
is a multiply-iterated class; I've written it here before. This one is, in my opinion, better than the previous ones, other than the annoying c++11-isms I had to use.