struct subtyping?

Austin Hastings ah08010-d at yahoo.com
Mon Oct 25 06:21:27 PDT 2010


On 10/24/2010 7:19 PM, spir wrote:
> On Sun, 24 Oct 2010 18:54:15 -0400
> bearophile<bearophileHUGS at lycos.com>  wrote:
>
>> spir:
>>
>>> But for any reason, this logic is not pushed to the point of providing type hierarchy by subtyping. It would have been great for me, since much of the common functionality is generic. Without a type hierarchy, I need to duplicate it on each struct type, which is _bad_ (as any programmer knows ;-).
>>
>> Can you explain your use case better? I am curious. I have used a hierarchy of structs in D in a small raytracer, to encode 3D objects.
>
> I cannot explain in detail, because it's still vague in my mind. It would be for a toy OO dynamic language. The root struct type would represent to root "element" (piece of data) type. Then, the whole D-struct hierarchy would mirror the source language's type hierarchy.
> I want a type hierarchy so that I can directly implement generic core language features (that a record can store any kind of element) and types (eg collections). Also, every element of the language itself would be a record-element, including types, methods, scopes...

I would recommend that you reconsider not wanting reference semantics 
for this. If you're doing a dynamic language, you probably don't want to 
represent "int" as a struct, but rather some BigInt or Scalar or some 
such. And then you almost immediately want to use pass-by-reference on that.

You might define a common record-keeping element that is value based, 
and store that in a struct in the lowest-level object class.

Also, keep in mind that the struct mechanism does not do dispatching at 
all. It simply knows what the type is, and invokes the appropriate 
function directly.

This is more performant, especially at the low level where VM ops would 
be implemented, but it also means you have to know the type in question. 
If you are doing some kind of switch on an opcode type, your opcodes may 
encode the type of the operands. But it would have to be a one-to-one 
encoding, because there is no virtual dispatch with structs. So 
push-string has to be different from push-int and push-float, for example.

On the other hand, you might make your object references a struct type, 
with the expectation that the set of operations defined on an object ref 
is constant. Then the object will respond to "methods" but the object 
reference struct would respond to "ops", and one "op" would be "call 
method".

=Austin


More information about the Digitalmars-d-learn mailing list