struct vs class for small math types?

Andrey Khropov andkhropov_nosp at
Tue Oct 24 15:19:49 PDT 2006

Bill Baxter wrote:

> Seems like struct is the way to go for implementing small math types like 3D
> vectors or quaternions that have POD semantics.

Have you looked at what's already available in this area (small math types): ?

> However, for example, with 4 doubles in a quaternion we're talking 32 bytes
> for just one of those guys.  Normally in C++ I would write operator overloads
> and such using 'const quat&' as the argument type to avoid copying the data
> on the stack.  Is there a way to do that in D? Should I be worried?

I think small functions like addition and such should be inlined anyway so it
shouldn't be an issue. However this depends on a particular compiler
implementation quality.

> The lack of constructors or usable initializers seems another issue for
> structs.  I guess I'm supposed to use static opCall to make something that
> looks like a constructor:
> static vector opCall(double x, double y, double z)
> {
>    vector ret;
>    ret.x = x; ret.y = y; ret.z = z;
>    return ret;
> }

I doesn't really understand why shouldn't constructors for structs be allowed:
look at C# - it's perfectly legal there.

People will use this static opCall hack anyway for that purpose.

> and opAdd then looks like
> vector opAdd(vector v) { return vector(x+v.x, y+v.y, z+v.z); }
> which makes the syntax for opAdd and the rest not so bad, but makes me more
> worried about extra temporaries created in an expression like vector c = a +
> b.

C++ doesn't address this problem too, but good compilers may optimize
temporaries away. Another option could be to use expression templates but D
doesn't support them as there's no possibility to overload '=' operator.

'non-optimal' is a politically correct term for s*it

More information about the Digitalmars-d-learn mailing list