[typing] Type-erasure re generics

Steven Schveighoffer schveiguy at yahoo.com
Wed Sep 29 11:11:53 PDT 2010


On Wed, 29 Sep 2010 13:44:32 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Wednesday, September 29, 2010 10:18:17 Pelle wrote:
>> On 09/29/2010 05:53 PM, Jesse Phillips wrote:
>> > The only benefit, which should be solve in another manner is having  
>> this
>> > code work:
>> >
>> > class A {}
>> > class B:A {}
>> >
>> > class Container(T) {}
>> >
>> > void main() {
>> >
>> >      Container!(A) a = new Container!(B)();
>> >
>> > }
>>
>> Sorry for falling off topic, but that code shouldn't work.
>>
>> a.insert(new A)
>
> Yeah. Having a container of one type should not be castable to a  
> container of
> another type. They are completely separate types even if they hold types  
> which
> have an is-a relationship. And your example shows one of the reasons  
> why. It's a
> fundamental aspect of the concept of generic containers, not a result of  
> the
> implementation. It _seems_ like it should work, but once you really get  
> into it,
> it quickly becomes apparent that it doesn't.

I think actually that concept is in the latest C# with type  
contra-variance.

Essentially, you should be able to implicitly cast Container!(B) to  
const(Container!(A)) conceptually, but actually you may have to require  
only pure calls (I don't think there's a way to do this).

I think C# deals with this via designating certain types on the template  
parameters as "input" or "output" types, and restricting functions from  
using types in the wrong direction.

-Steve


More information about the Digitalmars-d mailing list