[typing] Type-erasure re generics

Jonathan M Davis jmdavisProg at gmx.com
Wed Sep 29 12:16:28 PDT 2010


On Wednesday, September 29, 2010 11:54:30 Steven Schveighoffer wrote:
> I think it may have to be more than just const:
> 
> class C(T)
> {
>     static T globalval;
> }
> 
> class A {}
> class B : A {}
> 
> void foo(C!B c)
> {
>    const(C!A) c2 = c;
>    c2.globalval = new A;
> }
> 
> If the entire class is marked as pure (with pure defined as weak purity a
> la Don's idea) that might work as setting globalval would be illegal.

Ah. Once you get beyond arrays, you have the issue of the container type itself 
being different. Hmmm. For C#, you might be okay since they're all technically 
the same type anyway (and would share any globals), but for D, the two types 
could have absolutes nothing in common with one another. All class variables 
would be by definition local to each instantiation, so no const would not be 
enough.

But worse still, consider this: With templates, you could have a container type 
which used completely different implementations depending on the type(s) you use 
to instantiate it. It could use an array for ints, a hash table for floats, and a 
red-black tree for everything else. In such a case, would would it even _mean_ 
to try and assign one container type to another? Sure, if they're classes, and 
they share the same API, you may be able to get it to work thanks to the fact 
that you're dealing with references. But for structs? Forget it. Just because 
the types Array!int and Array!float are instantiated from the same template 
doesn't mean that they have anything in common other than the base name. The 
only way that you can even consider having containers be effectively in an 
inheritance hiercharcy because their elements are in an inheritence hiearchy is 
if the containers are classes. And since it looks like most - if not all - 
containers in Phobos are going to be structs, it quickly becomes a moot point 
for anything but arrays. With arrays, you could do it with just constness, I 
think. But for other container types? It _might_ be feasible with classes if you 
could somehow restrict access to all of their class variables and non-pure, 
static member functions, but it_won't work for structs.

- Jonathan M Davis


More information about the Digitalmars-d mailing list