Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cassert>
- #include <iterator>
- #include <array>
- #include <numeric>
- #include <vector>
- template<bool...> struct bool_pack{};
- template<class... Ts>
- using conjunction = std::is_same<bool_pack<true,Ts::value...>, bool_pack<Ts::value..., true>>;
- template<typename CheckType, typename... Ts>
- using AllOfType = typename std::enable_if<conjunction<std::is_convertible<Ts, CheckType>...>::value>::type;
- template <typename T, size_t Rank = 1>
- class ArrayView
- {
- using IndexType = std::ptrdiff_t;
- public:
- ArrayView(T* d, std::initializer_list<IndexType> l) :
- data(d)
- {
- assert(l.size() == Rank);
- std::copy(l.begin(), l.end(), bounds.data());
- SetStride();
- };
- template <typename...Ts, typename = AllOfType<IndexType, Ts...>>
- T& operator()(Ts...args)
- {
- return (*this)[{args...}];
- }
- size_t NumberOfElements()const
- {
- return std::accumulate(bounds.begin(), bounds.end(), 1, std::multiplies<>());
- }
- private:
- T& operator[](std::initializer_list<IndexType> l)
- {
- assert(Contains(l));
- assert(l.size() == Rank);
- return (*this)[Offset(l)];
- }
- T& operator[](size_t index) const
- {
- return *(data + index);
- }
- bool Contains(std::initializer_list<IndexType> l) const
- {
- bool contains = true;
- std::vector<IndexType> v(l);
- for (size_t i = 0; i < bounds.size() && contains; ++i)
- {
- contains = v[i] < bounds[i];
- }
- return contains;
- }
- void SetStride()
- {
- stride[Rank - 1] = 1;
- for (int dim = static_cast<int>(Rank) - 2; dim >= 0; --dim)
- {
- stride[dim] = stride[dim + 1] * bounds[dim + 1];
- }
- }
- IndexType Offset(std::initializer_list<IndexType> l) const
- {
- assert(l.size() == Rank);
- IndexType offset = 0;
- std::vector<IndexType> v(l);
- for (size_t i = 0; i < l.size(); ++i)
- {
- offset += v[i] * stride[i];
- }
- return offset;
- }
- T* data;
- std::array<IndexType, Rank> bounds;
- std::array<IndexType, Rank> stride;
- };
- template<typename T, typename...Dimensions>
- auto CreateArrayView(T* t, Dimensions...ds) -> ArrayView<T, sizeof...(ds)>
- {
- return ArrayView<T, sizeof...(ds)>(t, {ds...});
- }
- int main()
- {
- const auto r = 5;
- const auto c = 2;
- const auto l = r*c;
- int i[l] =
- {0, 1,
- 2, 3,
- 4, 5, 6, 7, 8, 9
- };
- auto v = CreateArrayView(i, r, c);
- std::cout << v(4, 1) << std::endl;
- v(4, 1) *= 2;
- std::cout << v(4, 1) << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement