我有一个HashTable,我需要一些方法来返回一个not_found结果. type TCellT = record ..... property key: cardinal read FKey write FKey; property data: T read FData write FData; end; THashTableT = class(TEnumerableT) private FCell
type TCell<T> = record ..... property key: cardinal read FKey write FKey; property data: T read FData write FData; end; THashTable<T> = class(TEnumerable<T>) private FCells: array of TCell<T>; FEmpty: T; ... constructor Create(InitialSize: cardinal); overload; function Lookup(key: cardinal): T; ... end; constructor THashTable<T>.Create(InitialSize: cardinal); begin inherited Create; // Initialize regular cells FArraySize:= InitialSize; Assert((FArraySize and (FArraySize - 1)) = 0); // Must be a power of 2 SetLength(FCells, FArraySize); FillChar(FEmpty, SizeOf(FEmpty), #0); //Superfluous I know, just there to //demonstrate the point. end;
鉴于上述结构,如何返回未找到的结果?
如果我有指针,我会返回一个指向T的零指针.
但是不允许指向泛型类型的指针.
所以我想出了下面的解决方案:
function THashTable<T>.Lookup(key: cardinal): T; var Cell: NativeUInt; begin if (key <> 0) then begin // Check regular cells Cell:= First_Cell(IntegerHash(key)); while (true) do begin if (FCells[Cell].key = key) then Exit(FCells[Cell].data); if not (FCells[Cell].key = 0) then Exit(FEmpty); <<-- is this correct? Cell:= Circular_Next(Cell); end; end else begin Result:= FEmpty; <<--- Can I return an empty generic like this? end; end;
我可以返回零初始化的泛型来表示没有结果吗?
或者我会遇到结构化类型(类/记录/变体/字符串等)的问题.
请注意,当T是整数时,我确实理解了歧义.零可能是一个有效的值,因此它与not_found无法区分.
我并不担心这些结果.