Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Array constraint missing for generics.

2 views
Skip to first unread message

Skybuck Flying

unread,
Jan 13, 2023, 5:22:07 AM1/13/23
to
(Dynamic) array constraint for generics could and would be usefull to declare a parameterized type which is usefull for

TrySetLength function.

The TrySetLength function should only accept generic types which are of the form of a dynamic array (of some type), and not classes, not records, etc.

Furthermore in this specific case it might also be usefull if multiple constrains can be combined such that the TrySetLength parameterized type can accept either a dynamic array or a string, unless a string is already considered a dynamic array, but I believe Delphi and it's runtime interpret strings in a special, especially the short string type, which is a static array.

So maybe a more general "array constrain for generics" would be enough.

So either it's a static or dynamic array.

I can also imagine that in the future it might be handy if the array constrain can be specified further to only apply to dynamic arrays, or only to static arrays and such, so maybe having those options as well would be nice.

Syntax could maybe look something like:
class function TTrySetLengthHelper.TrySetLength<ParameterType : array of any;>( var Para : ParameterType ) : boolean;
var
LTypeInfo: PTypeInfo;
begin
// I intended to use run time information to get the type info required for
// DynArraySetLength, etc, this is just test code...
LTypeInfo := TypeInfo(ParameterType);
WriteLn(LTypeInfo.Name);
result := true;
end;

For now I think array of any constraint will do.

If you really must have a dynamic array constraint, I don't really see a way to diversify between static and dynamic arrays, except from maybe using a pre-defined type, but then it would loose it's generic ability which would suck.

Ofcourse the keyword dynamic and static could be introduced and then used as follows:

class function TTrySetLengthHelper.TrySetLength<ParameterType: dynamic array of any>( var Para : ParameterType ) : boolean;

class function TTrySetLengthHelper.TrySetLength<ParameterType: static array of any>( var Para : ParameterType ) : boolean;

So it might still be possible. I don't want it to become to much like c++, but in this case I guess it's not so bad, it's ok.

Good luck with implementing this functionality !

(Maybe for the time being I can find some kind of method to determine if a passed variable is of type array and then at least if it's not then TrySetLength could at least throw an exception instead of returning just false, because that might be miss leading and pretending to be out of memory, while in reality the programmer made a programming mistake.

Bye for now,
Skybuck.
0 new messages