레코드 타입 제약
레코드 타입 제약
Delphi 모드에서는 레코드 타입 제약(record type restriction)이 단순 타입의 사용도 허용해요.
본문
Type
TList<_T : record> = class(TObject)
public
Type TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
TIntList = TList<Integer>;
제약은 타입을 특수화(specialize)할 때 적용돼요. 즉 타입을 특수화할 때 활성화된 모드가 단순 타입을 쓸 수 있는지를 결정해요. 레코드로의 제약이 ObjFPC 모드에서 컴파일됐다면, Delphi 모드로 작성된 코드라도 단순 타입으로 특수화할 수 있어요.
예를 들어:
unit tg;
interface
{$mode objfpc}
Type
generic TList<_T : record> = class(TObject)
public
Type TCompareFunc = function(const Item1, Item2: _T): Integer;
Public
data : _T;
procedure Add(item: _T);
procedure Sort(compare: TCompareFunc);
end;
implementation
generic procedure TList<_T>.Add(item: _T);
begin
end;
generic procedure TList<_T>.Sort(compare: TCompareFunc);
begin
end;
end.
위 코드는 {$MODE Delphi}에서 다음처럼 쓸 수 있어요.
{$mode delphi}
uses tg;
Type
TIntList = TList<Integer>;
begin
end.
더 알아보기
- 제네릭 문법 요소(Syntax elements)
- 타입 오버로드(Type overloads)