opCast using in template struct

Simen Kjaeraas simen.kjaras at gmail.com
Thu Oct 18 08:22:21 PDT 2012


On 2012-10-18, 16:54, Oleg wrote:

> Hello. How to cast template struct to itself?
>
> struct vec(string S,T=double)
> {
>      T[S.length] data;
>      auto opCast(string K,E)()
>          if( S.length == K.length &&
>               is( T : E ) )
>      {
>          vec!(K,E) ret;
>          foreach( i, ref m; ret.data )
>              m = data[i];
>          return ret;
>      }
> }
>
> unittest
> {
>      alias vec!"xyz" dvec3;
>      alias vec!("rbg",float) fcol3;
>      auto a = dvec3([1,2,3]);
>      auto b = fcol3();
>      b = a; #1
>      assert( b.data == [1,2,3] );
> }
>
> #1 Error: cannot implicitly convert expression (a)
> of type vec!("xyz") to vec!("rbg",float)

I don't see a cast there. Do you?

What you want is to overload the assignment operator, opAssign:

struct vec(string S,T=double)
{
     T[S.length] data;
     void opAssign(string K,E)(vec!(K,E) value)
         if( S.length == K.length &&
              is( E : T ) )
     {
         foreach( i, ref m; value.data )
             data[i] = m;
     }
}

unittest
{
     alias vec!"xyz" dvec3;
     alias vec!("rbg",float) fcol3;
     auto a = dvec3([1,2,3]);
     auto b = fcol3();
     b = a; #1
     assert( b.data == [1,2,3] );
}

-- 
Simen


More information about the Digitalmars-d-learn mailing list