July 11, 2015 Re: Array operations with array of structs | ||||
---|---|---|---|---|
| ||||
Posted in reply to Peter | On Saturday, 11 July 2015 at 13:31:12 UTC, Peter wrote:
> The postblit can only not take @nogc due to the array duplication which is understandable.
> I think the postblit might be redundant anyway since the struct is built on a static array so there is no possibility of two different Vect3s "pointing" to the same data.
> Can someone confirm or does the postblit do anything else?
The postblit is pointless, yes. The `.dup` copies from one location to another, only for the assignment to copy everything back to the original location; and then the new array is discarded.
|
July 11, 2015 Re: Array operations with array of structs | ||||
---|---|---|---|---|
| ||||
Posted in reply to Peter | 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[]'
}
|
Copyright © 1999-2021 by the D Language Foundation