The biggest problem with the generic type definitions we have seen so far is that there is very little you can do with objects of the generic class type. There are two techniques you can use to overcome this limitation. The first is to make use of the few special functions of the runtime library that spe cifically support generic types; the second (and much more powerful) is to define generic classes with constraints on the types you can use.
I'll focus on the first part in this section and constraints in the next section. As I mentioned, there is brand new function and two classic ones that have been specifically modified to work on the parametric type (t) of generic type definition:
The GenericTypeFunc example has a generic class showing the three generic type functions in action:
TSampleClass <T> = class private data: T; publ ic procedure Zero;
function GetDataSize: Integer; function GetDataName: string;
function TSampleClass<T>.GetDataSize: Integer; begi n
function TSampleClass<T>.GetDataName: string; begi n
procedure TSampleClass<T>.Zero; begi n
73 This zero-initialized memory has the same value of a global variable of the same type. Differently from local variables, in fact, global ones are initialized to "zero" by the compiler.
In the GetDataName method I used the GetTypeName function (or the TypInfo unit) rather than directly accessing the data structure because it performs the proper UTF-8 conversion from the encoded ShortString value holding the type name.
Given the declaration above, you can compile the following test code, that repeats itself three times on three different generic type instances. I've omitted the repeated code, but show the statements used to access the data field, as they change depending on the actual type: var tl: TSampleClass<Integer>; t2: TSampleClass<string>; t3: TSampleClass<double>; begi n tl := TSampleClass<Integer>.Create; tl.Zero;
t2 := TSampleClass<string>.Create;
t3 := TSampleClass<double>.Create;
Running this code (from the GenericTypeFunc program) produces the following output:
TSampleClass<Integer> data: 0 type: Integer size: 4
type: string size: 4
TSampleClass<double> data: 0 type: Double size: 8
Notice that you can use the generic type functions also on specific types, outside of the context of generic classes. For example, you can write:
Was this article helpful?
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.