Reputation: 76703
If I have a class declaration like this one:
MyCollection<T: TBaseCopyable, constructor> = class
What does the keyword constructor
do?
Doesn't every class have a constructor already, what is it up doing there?
Upvotes: 5
Views: 189
Reputation: 613272
It is a generic constraint.
Constraints can be associated with a type parameter of a generic. Constraints declare items that must be supported by any particular type passed to that parameter in a construction of the generic type.
This particular constraint is the constructor constraint:
A type parameter may be constrained by zero or one instance of the reserved word "constructor". This means that the actual argument type must be a class that defines a default constructor (a public parameterless constructor), so that methods within the generic type may construct instances of the argument type using the argument type's default constructor, without knowing anything about the argument type itself (no minimum base type requirements).
In a constraint declaration, you can mix "constructor" in any order with interface or class type constraints.
In my opinion it's a largely useless feature. Every time I've written a generic container class that wishes to instantiate members, I've found that I needed to be able to pass parameters to the constructor. I have absolutely no idea why the feature exists in this crippled form.
There is a well-known technique that allows generic containers to instantiate members, discussed here: Generics constructor with parameter constraint?
Upvotes: 4