With C++ AMP, you can use array or array_view to work with data in a multi-dimensional way, which often reflects your algorithm more naturally. Sometimes, however, you might need to reshape the data to adapt data to an existing interface or to use data generated by a factory library in your algorithms. For example, you might want to take advantage of a library that only provides APIs for linear containers although your data sits in N-dimensional arrays or array_views. In this blog post, I will introduce you to the view_as function available on array and array_view, which is useful for these scenarios.
Following is the view_as signature.
template <typename T, int N>class array{ template <int K> array_view<T,K> view_as(extent<K> viewExtent) restrict(cpu,amp) template <int K> array_view<const T,K> view_as(extent<K> viewExtent) const restrict(cpu,amp) };template <typename T>class array_view<T,1>{template <int K> array_view<T,K> view_as(extent<K> viewExtent) const restrict(cpu,amp);};template <typename T>class array_view<const T,1>{ template <int K> array_view<const T,K> view_as(extent<K> viewExtent) const restrict(cpu,amp);};
Note the following facts for the view_as function:
Now let’s see a simple example that illustrates the usage of view_as to adapt data to an existing interface. For example, we have a library that provides the following API that fills the given array_view of rank 1 with random numbers:
void random_fill(array_view<float,1> in);
Now, if you have a 2-dimentional array with float elements, you could still use this API to do initialization via view_as like:
void fill(array<float,2> a) { random_fill(a.view_as<1>(extent<1>(a.extent.size())));}
Another real world example would be to adapt 2D image data to a histogram calculator, which is usually a 1D algorithm.
This concludes my introduction to view_as. My next post will describe a somewhat related API: reinterpret_as. As always, you are welcome to ask questions and provide feedback below or on our MSDN forum.