struct inheritance, L-value return

cschueler cschueler_member at pathlink.com
Mon Jun 12 18:00:14 PDT 2006


A little report on recent tamperings with D.
I often deal with primitive types which are "vector spaces". Examples

* 3D-vectors
* colors
* quaternions
* matrices.

While these are distinct types with distinct operations, they all have in common

that they can add and subtract members of their kin, and multiply them with a
scalar. They also have a zero (neutral) element.
This is what the term vector space is mathematically about.

In the C++ world, I was so annoyed that I had to type the same boilerplate 
stuff over and over again for each of these types that I invented my "vector
space" template system. With this system it is possibly to declare a vector 
space type with minimum effort and have all the basic operations ready
to go.

It seems I cannot port this system to D with the current state of D.
The short story is I need either

- struct inheritance
or
- anonymous unions outside an aggregate in a mixin

I would prefer struct inheritance:

struct field
{
union { ... };
union { ... };
union { ... };
};

struct vectorspace : field
{
// have anonymous unions of "field" injected into this scope    
}

but I since there is no struct inheritance, I tried with mixins

template field
{
union { ... };
union { ... };
union { ... };
};

struct vectorspace
{
mixin field;        
}

But you cannot have anonymous unions outside a struct :/(
So I'm struck at this point.
Moreover, the mixin approach is not feasible because then 
you cannot make field a template parameter.

template( field )
{
struct vectorspace

only seem to work when field is a type, not a mixin.

I would like to weigh in for struct inheritance, since it seems a
trivial thing to allow. C programmers have often done this 
by declaring a variable of the base type as the first member
of the struct. So I was a little surprised that D has no
inheritance for plain data structs.

There is more missing in D that prevents me to port the
system fully:

- explicit return by reference (return an L-value)
- struct constructors

These are not showblockers, but missing them is ugly!
I see from the archives that struct constructors have been 
discussed already, so count me as another vote for struct
constructors here.

The explicit L-value return however I think is an important
concept that is missing with subtle implications. Without it,
user defined types can never be made transparent to 
builtin types. Consider:

int a;
(+a) = 3;

The unary plus operator returns an L-value, so the assignment
can take place. In C++, you can define the unary + operator
to behave the same for your type, by defining both R-value
and L-value operator:

// R-value unary +
const mytype &operator +( const mytype &object )
{ return object; }

// L-value unary +
mytype &operator +( mytype &object )
{ return object; }

In D, you can only do the R-value version.






More information about the Digitalmars-d mailing list