Ich habe eine generische Klasse TSmartArray, die ich in einer for-in-loop ansprechen können möchte. Wie definiere ich einen Enumerator dafür?
Mein Problem ist, dass man eine Im-Voraus-Deklaration benutzen muss, die bei Generischen Typen nicht geht oder anders aussieht. Das Beispiel in der Freepascal-Wiki sieht so aus:
Code: Alles auswählen
TEnumerableTree = class; // Vor-Deklaration
TTreeEnumerator = class
…
constructor Create(ATree: TEnumerableTree);
Ich schließe daraus, dass die Voraus-Deklaration nicht geklappt hat.
Code: Alles auswählen
unit SmartArray;
{$mode objfpc}{$H+}
interface
type
generic TSmartArray<T> = class;
generic TSmartArrayEnum<T> = class
type
TContainer = specialize TSmartArray<T>; // Error: Specialization is only supported for generic types
private
FIndex: SizeInt;
function GetCurrent: T;
public
constructor Create(ASmartArray: TContainer);
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
generic TSmartArray<T> = class
type
TEnum = specialize TSmartArrayEnum<T>;
private
…
public
constructor Create;
procedure Add(N: T);
function GetEnumerator: specialize TSmartArrayEnum<T>;
procedure Clear;
destructor Destroy;
property Length: SizeInt read FCount;
property Elements[Index: SizeInt]: T read GetElement write SetElement; default;
property Low: SizeInt read FLow write SetLow;
property High: SizeInt read GetHigh;
property MemSize: SizeInt read GetBufSize write SetMemSize;
end;
implementation