gpt4 book ai didi

delphi - 将泛型与不同的约束相结合

转载 作者:行者123 更新时间:2023-12-03 14:59:39 24 4
gpt4 key购买 nike

我有这个原子乐观初始化类:

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 并相应地继续。

我不太喜欢这个想法,我正在寻找更好的方法。

最佳答案

您似乎无法指定“类或接口(interface)”类型的约束。因此,最简单的解决方案似乎是放弃约束(您可以使用 RTTI 在运行时强制执行它)。

对于 RTTI 方法,您可以使用 TypeInfo功能:

uses
..., TypInfo;

class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpT: T;
begin
if not assigned(PPointer(@storage)^) then begin
tmpT := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpT)^, nil) = nil then begin
case PTypeInfo(TypeInfo(T))^.Kind of
tkInterface:
PPointer(@tmpT)^ := nil;
tkClass:
TObject(tmpT).Free;
else
raise Exception.Create('Atomic<T>.Initialize: Unsupported type');
end;
end;
end;
Result := storage;
end;

关于delphi - 将泛型与不同的约束相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com