Issue with template function

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 18:18:01 PST 2015


> The original code I was using was written in Java, and only had 
> a method for strings. This is closer to what I wanted. My unit 
> tests were just going back and forth with readString function, 
> so I was completely missing this for other types. Nice catch!
>
> There were a couple issues with your code so I've included the 
> corrected version:
>

That's what I get for replying at 11pm =p
>     ubyte[] toUbytes(T)(T[] arr)
>     {
>         if (arr is null)
>         {
>             return null;
>         }
>
>         ubyte[T.sizeof] buffer;
>         ubyte[] result = new ubyte[arr.length * T.sizeof];
>
>         foreach (i, val; arr)
>         {
>             buffer[] = cast(ubyte[T.sizeof])(&(arr[i]))[0 .. 
> T.sizeof]; // Parenthesis and missing semicolon
>             result[i * T.sizeof .. (i * T.sizeof) + T.sizeof] = 
> buffer; // Specify appropriate slice for buffer to be inserted 
> into
>         }
>
>         return result;
>     }
  thinking about it again this can be done in a single memcpy

      ubyte[] toUbytes(T)(T[] arr)
      {
          if (arr is null)
          {
              return null;
          }

          ubyte[] result = new ubyte[arr.length * T.sizeof];

         memcpy(result.ptr, arr.ptr , arr.length * T.sizeof);
         return result;
     }

and an asUbytes can be done as a cast

      ubyte[] toUbytes(T)(T[] arr)
      {
          if (arr is null)
          {
              return null;
          }
          return cast(ubyte[]) arr.ptr [0 .. arr.length * 
T.sizeof];
      }


More information about the Digitalmars-d-learn mailing list