我有一个不受限制的通用类型Atomic,它实现了一个初始化器(详见我之前的问题)。
type
Atomic<T> = class
type TFactory = reference to function: T;
class function Initialize(var storage: T; factory: TFactory): T;
end;
现在我想编写一个简化的Initialize函数,该函数将从T中获取类型信息(前提是typeof(T)为tkClass),并使用默认构造函数创建新实例(如果需要)。
遗憾的是,这种方法失败了:
class function Atomic<T>.Initialize(var storage: T): T;
begin
if not assigned(PPointer(@storage)^) then begin
if PTypeInfo(TypeInfo(T))^.Kind <> tkClass then
raise Exception.Create('Atomic<T>.Initialize: Unsupported type');
Result := Atomic<T>.Initialize(storage,
function: T
begin
Result := TClass(T).Create; // <-- E2571
end);
end;
end;
编译器报错 E2571 类型参数 'T' 没有类或接口约束
。
我该如何欺骗编译器创建类 T 的实例?