template specialization for arrays

Timon Gehr timon.gehr at gmx.ch
Sat Oct 29 16:02:43 PDT 2011


On 10/30/2011 12:52 AM, J Arrizza wrote:
>     When using pattern matching, explicit template arguments are
>     necessary. You probably don't want that, the following code does not
>     need them:
>
>     void abc(T)(T parm1) if(!isDynamicArray!T)
>     {
>         writeln("simpleparm: ", parm1);
>     }
>
>     void abc(T)(T parm1) if(isDynamicArray!T){
>
>         writeln("array : ", parm1);
>     }
>
>
> The output is:
>
>     simpleparm: 1
>     dynamic array : str
>     dynamic array : [1, 2]
>
>
> which sort of makes sense, but doesn't fit my app. It is possible to
> treat a string as an array of characters, but in my case I  want to
> treat them as a single entity. The whole purpose of the array
> specialization is to search/manipulate/compare the individual elements
> of an array... except for strings.
>
> Ok, so I modified a little to take care of strings. But I also added
> another test for a static array and it's not playing nice anymore.
>
>     void abc(T, U=void) (T parm1)
>        {
>        writeln("simpleparm: ", parm1);
>        }
>
>     void abc(T: string) (T parm1)
>        {
>        writeln("string : ", parm1);
>        }
>
>     void abc(T:U[], U) (T parm1)
>        if (isDynamicArray!T)
>        {
>        writeln("dynamic array : ", parm1);
>        }
>
>     void abc(T:U[], U) (T parm1)
>        if (!isDynamicArray!T)  //tried isStaticArray as well here
>        {
>        writeln("static array : ", parm1);
>        }
>
>     void main(string[] args)
>        {
>          writeln("v4");
>          abc(1);
>          abc("str");
>          int[] arr = [1, 2];
>          abc(arr);
>          int[2] arr2 =[3, 4];
>          writeln("arr2 ", __traits(isStaticArray, arr2));
>          abc(arr2);
>        }
>
>
> Output is:
>
>     simpleparm: 1
>     string : str
>     dynamic array : [1, 2]
>     arr2 true
>     simpleparm: [3, 4]      // should be "static array: [3, 4]"
>
>
> John
>
>
>

This works:

void abc(T, U=void, size_t N=0) (T parm1) {
     writeln("simpleparm: ", parm1);
}

void abc(T: string) (T parm1) {
     writeln("string : ", parm1);
}

void abc(T:U[], U) (T parm1) if (isDynamicArray!T) {
     writeln("dynamic array : ", parm1);
  }

void abc(T:U[N], U, size_t N) (T parm1) {
     writeln("static array : ", parm1);
}

void main(string[] args) {
     abc(1);
     abc("str");
     int[] arr = [1, 2];
     abc(arr);
     int[2] arr2 =[3, 4];
     abc(arr2);
}


More information about the Digitalmars-d mailing list