[fpc-pascal] for-in loop cast
Ben Grasset
operator97 at gmail.com
Thu Sep 26 17:59:49 CEST 2019
On Thu, Sep 26, 2019 at 11:37 AM Ryan Joseph <genericptr at gmail.com> wrote:
> Question I’ve always had. Why do I need to cast “value” to “pointer"
> otherwise I get: Incompatible types: got "Pointer" expected “TObject”
> error?. I don’t find this very helpful and it doesn’t really make sense
> even.
>
Well, TObjectList is a descendant of TList, which is of course a
non-generic list of void pointers. The enumerator for TList that allows the
for-in loop to work, called TListEnumerator, as such obviously implements
GetCurrent as returning "pointer".
TObjectList doesn't have its own enumerator implementation on top of the
TList one or anything like that, so when you use for-in on TObjectList,
you're using the pointer-based TList one.
The fix for this is simple IMO: use a generic list class instead. For
example, if you want something that works exactly like your code example,
you can specialize TObjectList from Generics.Collections literally *with*
TObject:
type
TBaseObjectList = TObjectList<TObject>;
var
list: TBaseObjectList;
value: TObject;
begin
for pointer(value) in list do
;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20190926/7ebd63de/attachment.html>
More information about the fpc-pascal
mailing list