Array operations with array of structs

Peter via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 11 07:29:10 PDT 2015


On Saturday, 11 July 2015 at 13:31:12 UTC, Peter wrote:
> So after looking into it a little bit...

So now I'm trying to multiply the array by a double but it's 
giving incompatible type errors. opBinary, opBinaryRight, and 
opOpAssign are defined.

I have:
struct Vector3 {
     public double[3] _p;
     @nogc this(in double[] p){
         switch ( p.length ) {
         case 0: _p[0] = _p[1] = _p[2] = 0.0; break;
         case 1: _p[0] = p[0]; _p[1] = _p[2] = 0.0; break;
         case 2: _p[0] = p[0]; _p[1] = p[1]; _p[2] = 0.0; break;
         default: _p[0] = p[0]; _p[1] = p[1]; _p[2] = p[2]; break;
         }
     }
     @nogc this(in double p0, in double p1=0.0, in double p2=0.0){
         _p[0] = p0;
         _p[1] = p1;
         _p[2] = p2;
     }
     @nogc this(in Vector3 other){
         _p[] = other._p[];
     }
     Vector3 opBinary(string op)(in Vector3 rhs) const
         if (op == "+")
     {
         Vector3 result;
         result._p[] = this._p[] + rhs._p[];
         return result;
     }
     Vector3 opBinary(string op)(in double rhs) const
         if (op == "*")
     {
         Vector3 result;
         result._p[] = this._p[] * rhs;
         return result;
     }
     Vector3 opBinaryRight(string op)(in double lhs) const
         if (op == "*")
     {
         Vector3 result;
         result._p[] = this._p[] * lhs;
         return result;
     }
     //...
     pure nothrow @trusted @nogc ref Vector3 opAssign(ref Vector3 
rhs)
     {
         _p[] = rhs._p[];
         return this;
     }
     pure nothrow @trusted @nogc ref Vector3 opAssign(Vector3 rhs)
     {
         _p[] = rhs._p[];
         return this;
     }
     @nogc ref Vector3 opOpAssign(string op)(in double rhs)
         if (op == "*")
     {
         this._p[] *= rhs;
         return this;
     }
     //...
}
unittest{
     auto a = Vector3([2.0, 2.0, 0.0]);
     auto b = Vector3([1.0, 2.0, 1.0]);
     Vector3[] c = [a];
     Vector3[] d = [b];
     Vector3 e = a + b; //fine
     Vector3[] f;
     f[] = c[] + d[]; //fine

     e = 2*a; //fine
     e = 3.0*a; //fine
     f[] = 2*c[]; //Error: incompatible types for ((2) * (c[])): 
'int' and 'Vector3[]'
     f[] = 3.0*c[]; //Error: incompatible types for ((3.00000) * 
(c[])): 'double' and 'Vector3[]'
}




More information about the Digitalmars-d-learn mailing list