[英]How can I declare a pointer based on a generic type?
我有一個這樣的課程:
type A = class
procedure<T> DoStuff(tPtr: ^T);
end;
但是當我嘗試編譯時,Delphi 給了我這個錯誤:
[DCC Error] RPML.pas(57): E2029 Identifier expected but '^' found
如何在 Delphi 過程中使用指向參數化類型的指針? 我不想讓整個班級成為模板班級。
為此,您需要在泛型類中將指針類型聲明為嵌套類型:
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 的回答為您提供了一個類函數,但在評論中您聲明您正在尋找一個普通的成員函數。
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 中,如果沒有通用解決方案,就無法有效地完成任何非常有用的事情。
我很感激任何建議,並很樂意編輯答案以適應它們。
您可以將泛型參數從類移動到方法,並使用 var 代替指針類型:
type
TMyGeneric = record
class procedure DoStuff<T>(var aParam: T); static;
end;
var
int : Integer;
s : string;
...
TMyGeneric.DoStuff<Integer>(int);
TMyGeneric.DoStuff<string>(s);
編輯:不幸的是,當使用 var 參數時,Delphi 編譯器似乎無法執行類型推斷,這使得必須在方法調用上使用 <..> 顯式指定泛型參數類型。
如果沒有“var”,<..> 可以省略(但是該方法不能再修改傳入的變量)。
type
Pointer<T> = record
public type
Ty = ^T;
end;
現在你可以在任何地方使用這個通用指針
type A = class
procedure<T> DoStuff(tPtr: Pointer<T>.Ty);
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.