为此,您需要将指针类型声明为泛型类中的嵌套类型:
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);
托尔斯滕的答案为您提供了一个类函数,但在评论中您声明您正在寻找一个普通的成员函数。
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 中,您究竟如何能够用它来做任何非常有用的事情,如果没有通用的解决方案,就无法有效地完成这些事情。
我很感激任何建议,并很乐意编辑答案以适应它们。