cpp-proposals-pub icon indicating copy to clipboard operation
cpp-proposals-pub copied to clipboard

P0009: Consider adding conversion to std::array

Open mhoemmen opened this issue 3 years ago • 2 comments

A colleague asked if we could add operator std::array<value_type, rank()> to mdspan. It would have to be constrained on rank() == 1 and static_extent(0) != dynamic_extent. The mdspan_to_array function that follows illustrates an implementation approach.

https://godbolt.org/z/h6PeTdzPo

#include <https://raw.githubusercontent.com/kokkos/mdspan/single-header/mdspan.hpp>
#include <array>
#include <cassert>
#include <iostream>
#include <type_traits>
#include <utility>

namespace stdex = std::experimental;

template<class ElementType, class IndexType, std::size_t N, class Accessor>
requires( N != std::dynamic_extent )
std::array<ElementType, N>
mdspan_to_array(stdex::mdspan<ElementType, stdex::extents<IndexType, N>, stdex::layout_right, Accessor> m)
{
    return [&]<std::size_t ... Indices>(std::integer_sequence<IndexType, Indices...>) {
        return std::array<std::remove_cv_t<ElementType>, N>{ m[Indices]... };
    }( std::make_integer_sequence<IndexType, N>() );
}

int main() {
  std::array d{ 0, 1, 2, 3, 4, 5, 6, 7, 8 };

  stdex::mdspan<int, stdex::extents<std::size_t, 9>> d_md{d.data()};
  auto d_arr = mdspan_to_array(d_md);
  static_assert(std::is_same_v<decltype(d), decltype(d_arr)>);
  for(std::size_t k = 0; k < d.size(); ++k) {
    assert(d_arr[k] == d[k]);
  }
  return 0;
}

mhoemmen avatar Jun 30 '22 20:06 mhoemmen

I don't think that mdspan -> std::array makes sense. mdspan is non-owning, std::array isn't. You can't convert std::string_view to std::string or construct a std::array from a std::span either.

crtrott avatar Jul 05 '22 17:07 crtrott

In either case: if you want this we need to propose std::span -> std::array first, and considering that we don't even have std::mdspan -> std::span that thing also should come first. There are reasons we removed the latter again.

crtrott avatar Jul 05 '22 17:07 crtrott