Joh*_*ica 3 delphi generics delphi-xe2
我有一个HashTable,我需要一些方法来返回not_found结果.
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;
Run Code Online (Sandbox Code Playgroud)
鉴于上述结构,我该如何返回not found结果?
如果我有指针,我会返回nil指针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;
Run Code Online (Sandbox Code Playgroud)
我可以将零初始化通用返回到什么意思no result?
或者我会遇到结构化类型(类/记录/变体/字符串等)的问题.
请注意,我确实理解T整数时的歧义.零可能是一个有效的值,因此它与not_found无法区分.
我并不担心这些结果.
| 归档时间: |
|
| 查看次数: |
1390 次 |
| 最近记录: |