Making containers that "go both ways"

janderson askme at me.com
Sat Jan 26 11:05:00 PST 2008


Bill Baxter wrote:
> janderson wrote:
>> Bill Baxter wrote:
>>  > Hey,
>>  > Just wanted to throw this idea out for comment.
>>  > I find I can't really decide whether a container class should be a 
>> struct or a class.  Struct feels right if I want minimal overhead and 
>> something that works more like a built-in datatype.  But class feels 
>> right for situations where I'm less concerned about performance
>>
>>
>> Personally I'd make it a class.  Yes its going to go on the heap 
>> however the resizeable array part or whatever the container contains, 
>> will probably go on the heap anyway.
>>
>> , and
>>  > also offers the additional ability to extend the basic 
>> functionality via subclassing.
>>
>> I think you should avoid thinking about subclassing like this.  Using 
>> mixins or components is a much better idea then subclassing. 
>> Subclassing should normally be used for polymorphism.
> 
> Yeh, I don't actually ever do that myself, but I hear that some people 
> do, at least in other languages.  That's why I mentioned it.  Anyway, if 
> I subclass Container to attach some additional info it, or do something 
> slightly different, but still pass it to the original Container-using 
> code how would that that not constitute subclassing for polymorphism?
> 
> But it's strange you say "make it a class" and then turn around and say 
> "but don't use the main property of classes that distinguish them from 
> structs".  If you want to discourage subclassing of containers, what 
> could be better than making them structs so that it's actually impossible?

A good point.

> 
> 
>>  > So something I did (a while back now...) was to create some 
>> containers in OpenMesh/D that use mixins for all their guts, and 
>> provide both struct and class wrappers for them.
>>  >
>>  > It seems to me like that might be the "right" way to do containers 
>> in D. Somewhat unfortunately, because it's more complicated than just 
>> writing one or the other.
> 
>> This may help:
>> http://www.artima.com/intv/goldilocks3.html
> 
> Not really.  He's talking about C++, where classes and structs are the 
> same thing.
> """
> Bjarne Stroustrup: My rule of thumb is that you should have a real class 
> with an interface and a hidden representation if and only if you can 
> consider an invariant for the class.
> """
> The distinction he's making is between making everything public vs 
> having private data members with API functions to do all the 
> manipulation.  That choice applies equally to either structs or classes 
> in D.

I guess I'm still thinking C++.  I still see struts as privative data 
types where all the members are public and classes as more complex 
datatypes which validates itself.

> 
> --bb



More information about the Digitalmars-d mailing list