Swap furthest element type of an array

Timon Gehr timon.gehr at gmx.ch
Mon Jun 18 11:16:15 PDT 2012


On 06/18/2012 06:29 PM, Andrej Mitrovic wrote:
> I just had a need for this but couldn't find it in Phobos:
>
> import std.stdio;
> import std.traits;
> import std.range;
>
> template SwapElem(Arr, Type)
> {
>      static if (isArray!(ElementType!Arr))
>      {
>          static if (isDynamicArray!Arr)
>              alias SwapElem!(ElementType!Arr, Type)[] SwapElem;
>          else
>              alias SwapElem!(ElementType!Arr, Type)[Arr.length] SwapElem;
>      }
>      else
>      {
>          static if (isDynamicArray!Arr)
>              alias Type[] SwapElem;
>          else
>              alias Type[Arr.length] SwapElem;
>      }
> }
>
> void main()
> {
>      alias int[2][1] IntArr;
>      alias SwapElem!(IntArr, float) FloatArr;
>      writeln(typeid(FloatArr));  // float[2][1]
> }
>
> It doesn't handle complex declarations like "int[2]*[1]". It seems
> hard to do since I can't pass a naked pointer as a type to a template.
> Some other clever tricks would have to be used here. But it's a worthy
> start. If you can improve it feel free to do so. :)

template SwapElem(A, E){
     static if(is(A X:X[N],size_t N)) alias SwapElem!(X,E)[N] R;
     else static if(is(A X:X[])) alias SwapElem!(X,E)[] R;
     else static if(is(A X:X*)) alias SwapElem!(X,E)* R;
     else alias E R;
     alias R SwapElem;
}

pragma(msg, SwapElem!(int[]*[3][]*[2][]*[1][], float));


More information about the Digitalmars-d-learn mailing list