Array operations with array of structs

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 5 20:26:01 PDT 2015


On Monday, 6 July 2015 at 03:02:59 UTC, Nicholas Wilson wrote:
> On Monday, 6 July 2015 at 01:16:54 UTC, Peter wrote:
>> Hi,
>> I have a struct with arithmetic operations defined using 
>> opBinary but array operations with arrays of it don't work.
>>
>> struct Vector3 {
>>     public double[3] _p;
>>     ...
>>     Vector3 opBinary(string op)(in Vector3 rhs) const
>>     if (op == "+"){
>>         Vector3 result;
>>         result._p[] = this._p[] + rhs._p[];
>>         return result;
>>     }
>>     ...
>> }
>>
>> 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; // works
>>     Vector3[] f;
>>     f[] = c[] + d[]; // Error: invalid array operation 'f[] = 
>> c[] + d[]' because Vector3 doesn't support necessary 
>> arithmetic operations
>> }
>>
>> how can I get this to work?
>>
>> Thanks
>
> you need to define the slice operators. e.g.
>
> auto opSlice() // no parameters to get whole slice eg. a[]
>                       // can also define with opSlice(size_t i, 
> size_t j)
>                       // for access like a[ i .. j]
> {
>     return _p;
> }

whoops. it may be complaining about lack of opSliceAssign
i.e. `f[] =`

again define this with no parameters for the whole slice or two 
for a[i .. j] =
also note that you need to give memory for this array assignment 
to go.
eg.

>>     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; // works
>>     Vector3[] f;
>>     f[] = c[] + d[];

will likely crash because `f` doesn't point to any allocated 
memory.
initialising like
  Vector3[] f = [Vector3()];

  Enhancement Request to tell you the names of the missing methods 
required
filed at
  https://issues.dlang.org/show_bug.cgi?id=14772


More information about the Digitalmars-d-learn mailing list