我有這樣的原子樂觀初始化類仿製藥相結合:不同的約束
type
Atomic<T: IInterface> = class
type TFactory = reference to function: T;
class function Initialize(var storage: T; factory: TFactory): T;
end;
class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpIntf: T;
begin
if not assigned(storage) then begin
tmpIntf := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpIntf)^, nil) = nil then
PPointer(@tmpIntf)^ := nil;
end;
Result := storage;
end;
現在我想執行的對象相同的模式。
type
Atomic<T: class> = class
type TFactory = reference to function: T;
class function Initialize(var storage: T; factory: TFactory): T;
end;
class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpIntf: T;
begin
if not assigned(storage) then begin
tmpIntf := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpIntf)^, nil) = nil then
tmpIntf.Free;
end;
Result := storage;
end;
我可以在兩個不同的類中做這兩個,但我真的想把這兩個初始化器放在同一個傘下。 IOW,我理想喜歡用這個作爲
var
o: TObject;
i: IInterface;
Atomic<TObject>.Initialize(o, CreateObject);
Atomic<IInterface>.Initialize(i, CreateInterface);
我找不到任何好的解決方案。我得到的唯一想法是聲明類爲Atomic<T>
(沒有約束),然後以某種方式(不知道如何)在運行時檢查T的RTTI並相應地繼續。
我不太喜歡這個想法,我正在尋找更好的方法。
這似乎工作正常,謝謝! – gabr
歡迎,@ gabr,我很高興能幫上忙! –