Array operations with array of structs
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 5 20:02:57 PDT 2015
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;
}
More information about the Digitalmars-d-learn
mailing list