为此,您需要在泛型类中将指针类型声明为嵌套类型:
type
TMyGeneric<T> = class
type
P = ^T;
public
procedure DoStuff(tPtr: P);
end;
如果你想要一个类方法(即不是实例方法),你可以这样做:
type
TMyGeneric<T> = record
type
P = ^T;
public
class procedure DoStuff(tPtr: P); static;
end;
var
int: Integer;
...
TMyGeneric<Integer>.DoStuff(@int);
或者使用 var 参数:
type
TMyGeneric<T> = record
public
class procedure DoStuff(var a: T); static;
end;
对于永远不会被实例化的泛型类型,使用记录而不是类似乎很常见。
最后,在 Delphi 中,如果不使类成为泛型,就不能拥有泛型方法。换句话说,没有以下 C++ 模板代码的类似物:
Thorsten 的回答展示了如何在不使类泛型的情况下实现泛型方法,即以下 C++ 模板代码的 Delphi 类似物:
class C {
public:
template <typename T>
int SomeTemplateFunction(T* data) {
printf("Address of parameter is %p\n", data);
return 0;
}
};
int a;
char c;
C cinst;
cinst.SomeTemplateFunction<int>(&a);
cinst.SomeTemplateFunction<char>(&c);
Thorsten 的回答为您提供了一个类函数,但在您声明的 cmets 中,您正在寻找一个普通的成员函数。
type
TMyClass = class
public
procedure DoStuff<T>(var a: T);
end;
procedure TMyClass.DoStuff<T>(var a: T);
begin
end;
...
var
instance: TMyClass;
i: Integer;
s: string;
...
instance.DoStuff<Integer>(i);
instance.DoStuff<string>(s);
但是,我正在努力解决的问题是,在 Delphi 中,您究竟如何能够做任何非常有用的事情,而没有通用解决方案则无法有效地完成。
如果有任何建议,我将不胜感激,并很乐意编辑答案以适应它们。