Generic Type Instantiation

With the exception of some optimizations, every time you instantiate a generic type, a new type is generated by the compiler. This new type shares no code with different instances of the same generic type.

Let's look at an example (which is called GenericCodeGen). The program has a generic class defined as: type

TSampleClass <T> = class private data: T; publ ic procedure One; function ReadT: T; procedure SetT (value: T); end;

The three methods are implemented as follows (notice that the One method is absolutely independent from the generic type):

procedure TSampleClass<T>.One; begi n

function TSampleClass<T>.ReadT: T; begi n

procedure TSampleClass<T>.SetT(value: T); begi n data := value; end;

Now the main program uses the generic type mostly to figure out the inmemory address of its methods once an instance is generated (by the compiler). This is the code (which uses a helper Log function to show log strings in a Memo control):

procedure TForm30.ButtonlClick(Sender: TObject); var tl: TSampleClass<Integer>; t2: TSampleClass<string>; begi n tl := TSampleClass<Integer>.Create; tl.SetT (10);

tl.One;

t2 := TSamp1eClass<string>.Create;

t2.One;

IntToHex (PInteger(@TSamp1eClass<Integer>.SetT)A, 8)); Log ( 't2.SetT: ' +

IntToHex (PInteger(@TSamp1eClass<string>.SetT)A, 8));

IntToHex (PInteger(@TSamp1eClass<Integer>.One)A, 8)); Log ( 't2.One: ' +

IntToHex (PInteger(@TSamp1eClass<string>.One)A, 8));

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment