@@ -8,6 +8,7 @@ Authors: Ilya Yaroshenko
88Source: $(PHOBOSSRC std/_experimental/_ndslice/_slice.d)
99
1010Macros:
11+ SUBREF = $(REF_ALTTEXT $(TT $2), $2, std,experimental, ndslice, $1)$(NBSP)
1112T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
1213T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
1314STD = $(TD $(SMALL $0))
@@ -919,6 +920,55 @@ unittest
919920 assert (shape[1 ] == 0 );
920921}
921922
923+ /+ +
924+ Convenience function that creates a lazy view,
925+ where each element of the original slice is converted to the type `T`.
926+ It uses $(SUBREF selection, mapSlice) and $(REF_ALTTEXT $(TT to), to, std,conv)$(NBSP)
927+ composition under the hood.
928+ Params:
929+ slice = a slice to create a view on.
930+ Returns:
931+ A lazy slice with elements converted to the type `T`.
932+ +/
933+ template as (T)
934+ {
935+ // /
936+ auto as (size_t N, Range )(Slice! (N, Range ) slice)
937+ {
938+ static if (is (slice.DeepElemType == T))
939+ {
940+ return slice;
941+ }
942+ else
943+ {
944+ import std.conv : to;
945+ import std.experimental.ndslice.selection : mapSlice;
946+ return mapSlice! (to! T)(slice);
947+ }
948+ }
949+ }
950+
951+ // /
952+ unittest
953+ {
954+ import std.experimental.ndslice.slice : as;
955+ import std.experimental.ndslice.selection : diagonal;
956+
957+ auto matrix = slice! double ([2 , 2 ], 0 );
958+ auto stringMatrixView = matrix.as! string ;
959+ assert (stringMatrixView ==
960+ [[" 0" , " 0" ],
961+ [" 0" , " 0" ]]);
962+
963+ matrix.diagonal[] = 1 ;
964+ assert (stringMatrixView ==
965+ [[" 1" , " 0" ],
966+ [" 0" , " 1" ]]);
967+
968+ // / allocate new slice composed of strings
969+ Slice! (2 , string * ) stringMatrix = stringMatrixView.slice;
970+ }
971+
922972/+ +
923973Base Exception class for $(MREF std, experimental, ndslice).
924974+/
0 commit comments