Parameterized methods

Top  Previous  Next

New features since Delphi 7 > Generics > Parameterized methods

 

 

Methods can be declared with type parameters. Parameter types and result types can use type parameters.

 

type

  TFoo = class

    procedure Test;

    procedure CompareAndPrintResult<T>(X, Y: T);

  end;

 

procedure TFoo.CompareAndPrintResult<T>(X, Y: T);

var

  Comparer : IComparer<T>;

begin

  Comparer := TComparer<T>.Default; 

  if Comparer.Compare(X, Y) = 0 then

    WriteLn('Both members compare as equal')

  else

    WriteLn('Members do not compare as equal');

end;

 

procedure TFoo.Test;

begin

  CompareAndPrintResult<String>('Hello', 'World');

  CompareAndPrintResult('Hello', 'Hello');

  CompareAndPrintResult<Integer>(20, 20);

  CompareAndPrintResult(10, 20);

end;

 

procedure Test;

var

  F: TFoo;

begin

  F := TFoo.Create;

  F.Test;

  ReadLn;

  F.Free;

end;

 

->

 

//---------------------------------------------------------------------------

class TFoo : public System::TObject

{

  typedef System::TObject inherited;

public:

  void Test();

    template<typename T> void CompareAndPrintResult(T X, T Y);

public:

  TFoo() {}

  System::TClass ClassType() const;

};

//---------------------------------------------------------------------------

class TFoo : public TObject

{

  typedef TObject inherited;

public:

  void Test();

    template<typename T> void CompareAndPrintResult(T X, T Y);

public:

  TFoo() {}

  System::TClass ClassType() const;

};

//---------------------------------------------------------------------------

class TFooClassRef : public ClassRef<TFoo, TObjectClassRef> { };

TFooClassRef TFooClassRefInstance;

System::TClass TFoo::ClassType() const

{

  return &TFooClassRefInstance;

}

//---------------------------------------------------------------------------

template<typename T> void TFoo::CompareAndPrintResult(T X, T Y)

{

  IComparer<T> Comparer;

  Comparer = TComparer<T>.Default;   //  error

  if(Comparer.Compare(X, Y) == 0)

    WriteLn(L"Both members compare as equal");

  else

    WriteLn(L"Members do not compare as equal");

}

//---------------------------------------------------------------------------

void TFoo::Test()

{

  CompareAndPrintResult<String>(L"Hello", L"World");

  CompareAndPrintResult(L"Hello", L"Hello");

  CompareAndPrintResult<int>(20, 20);

  CompareAndPrintResult(10, 20);

}

//---------------------------------------------------------------------------

void Test()

{

  TFoo* F = nullptr;

  F = new TFoo();

  F->Test();

  System::ReadLn();

  delete F;

}

 

 

The function "TFoo::CompareAndPrintResult doesn't compile. It can be improved in C++Builder with:

 

System::Generics::Defaults::IComparer__1<T> Comparer; // abstract

Comparer = TComparer__1<T>().Default();

 

But the code still doesn't compile, because Comparer is abstract.

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content