delphi - Is this the correct way to return an empty generic value? -
i have hashtable , need way return not_found
result.
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 , (farraysize - 1)) = 0); // must power of 2 setlength(fcells, farraysize); fillchar(fempty, sizeof(fempty), #0); //superfluous know, there //demonstrate point. end;
given above structure, how return not found
result?
if had pointers, return nil
pointer t
.
pointers generic types not allowed.
so i've come solution below:
function thashtable<t>.lookup(key: cardinal): t; var cell: nativeuint; begin if (key <> 0) begin // check regular cells cell:= first_cell(integerhash(key)); while (true) begin if (fcells[cell].key = key) exit(fcells[cell].data); if not (fcells[cell].key = 0) exit(fempty); <<-- correct? cell:= circular_next(cell); end; end else begin result:= fempty; <<--- can return empty generic this? end; end;
can return zero-initialized generic mean no result
?
or run problems structured types of (classes/records/variants/strings etc).
note understand ambiguity when t
integer. 0 might valid value , indistinguishable not_found.
i'm not worried results.
what you're looking default(t)
, return 0 value type t.
Comments
Post a Comment