Why does D not have generics?

Q. Schroll qs.il.paperinik at gmail.com
Tue Jan 12 16:57:43 UTC 2021


On Monday, 11 January 2021 at 18:30:19 UTC, Ola Fosheim Grøstad 
wrote:
> On Monday, 11 January 2021 at 18:23:20 UTC, Q. Schroll wrote:
>> I don't want to be mistaken. I know what the differences of 
>> generics (cf. Java, C#) are and what templates (cf. D, C++) 
>> are. Maybe my question has obvious answers and I just don't 
>> see them.
>>
>> The only programming language I know of that has both, 
>> templates and generics, is C++/CLI and ones closely related.
>
> I think you are really talking about generics in Java and is 
> interpreting the semantic landscape through that lense?

Yes. But I'm not saying: Do exactly as Java does. I'm saying: 
Java has this very interesting concept that D might want to 
learn, too.

> C++ "concepts" is to a large extent syntactical sugar that 
> makes it easier to specify interfaces... so I don't think it 
> has a significant semantic impact. Mostly a usability impact.

You might have mistaken me. C++ has no generics in the sense I 
meant. Generics to me means not that List<A> and List<B> result 
in one List type; really, I care about much more semantics than 
implementation. C# will create two different List classes if A or 
B is a value type. C#'s generics are copied like templates; but I 
digress, because I don't care.

In C#, even if you require a generic type parameter is a value 
type (which you can and entails a template-like implementation 
under the hood), the compiler makes sure that everything in your 
generic type is semantically valid for every type argument 
satisfying the conditions you state.
For example, if you call T.method(), but no constraint says that 
T.method() exists, the compiler rejects the code. On the other 
hand, in C++ or D, if you call T.method() in a template and only 
test types that happen to have method(), everything is good 
between friends (Andrei's quote).
I'm not arguing you *always* want static checks, obviously DbI 
hardly works that way. All I'm saying is, the big thing generics 
would bring to D is **statically ensuring** that the requirements 
put on type parameters suffice for the implementation to be valid.


More information about the Digitalmars-d mailing list