struct vs class for small math types?

Bill Baxter dnewsgroup at
Tue Oct 24 17:39:29 PDT 2006

Andrey Khropov wrote:
> 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): 
> ?

Yeh, that's pretty good.  The great thing about 3D math routines though 
is that everyone can have their own.  :-)  Porting my own C++ classes 
over is more an exercise in figuring out how to work with D than 
anything else, though.  Maybe I'll use helix when I'm satisfied that 
I've got it.  The interface and coding conventions look pretty similar 
to my own, and it looks quite complete.  Actually the more I look at it 
the more I think I already get it, so I should just use Helix and move 
on to more challenging tasks.

Thanks for the link.

>> 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.

Ok.  I was hoping this was the answer.  And hopefully it actually works 
out to be true in practice with real compilers, too.

In the event that it's not the case, I assume I can always just make a 
parameter be a (Matrix44f*) and make users deal with having to pass (&m) 
as the value.  At least inside the function I can use '.' and pretend m 
is not a pointer!

Hmm I wonder if automatic conversion of value types to their 
corresponding pointer types would be a good idea?

Then you could have:
void doSomething(Matrix44f *a, Matrix44f *b)
and just call it like:

Matrix44f a,b;

That implicit conversion could also maybe get rid of that annoying & here:

   foreach(i; &a.iter) {..}

> 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.

I think this has been discussed before, but if you're willing to use ~= 
as your assignment operator or call some function like "eval", then you 
should be able to get pretty much the same benefit as with expression 

   x ~= a + b + c + d;
   x = eval(a + b + c + d);

I seem to recall there was something else holding back expression 
templates, though.


More information about the Digitalmars-d-learn mailing list