Template Trick

Ali Çehreli acehreli at yahoo.com
Wed Jun 12 14:52:45 PDT 2013


On 06/12/2013 02:47 PM, matovitch wrote:
> To be more precise the code below doesn't compile :
>
> struct Vector(T, uint N)
> {
>      alias T type;
>      enum dimension = N;
>      T data[N];
> }
>
> void func(V, V.type def_val) (uint i, V v)
> {
>      if (i < v.dimension) {
>          v.data[i] = def_val;
>      }
> }
>
> void main()
> {
>      alias Vector!(int, 3) Vec3i;
>      Vec3i v;
>      func!(Vec3i, 42)(2, v);
> }
>
> With the error message :
>
> test.d(8): Error: no property 'type' for type 'V'
> test.d(8): Error: V.type is used as a type
>
>

Here is one way:

void func(V, alias def_val) (uint i, V v)
     if (is (typeof(def_val == V.type)))
{
     if (i < v.dimension) {
         v.data[i] = def_val;
     }
}

Ali



More information about the Digitalmars-d-learn mailing list