From Free Pascal wiki
Revision as of 10:08, 29 October 2010 by Chronos (talk | contribs) (New page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Templates is simple mechanism to solve problem of writing duplicate code to implement general class for specific type in strong typed language. It is used mainly for base non-object types as in case of objects inheritance of single base class TObject can be used to build general classes. In advanced languages templates are replaced by native language implementation called generics. Native implementation of generics in FPC 2.4.0 is not complete neither practically usable yet. Then templates could be used temporary in the meantime.


Classical example of basic generic class is list of items. Current Free Pascal offer three ways of use lists:

  • array of - classical dynamic array structure which can hold dynamic items of same type. Items are accessible by direct addressing SomeArray[Index]. SetLength and Length functions are used to handle size.
  • TList - objective way where class handle all list operations. Implementation in LCL keep compatibility with VCL where TList holds list of Pointers. If list of different item type is desired complete new class have to be copied and rewrited or typecasting have to be used in every place where list item is referenced. Typecasting is not effective e.g. Pointer(Byte) and not type safe Pointer(Int64). TList index is of type Integer. If Int64 or SmallInt index is needed than class have to be copied and rewrited.
  • TCollection - is more generic and type safe but heavier solution for storing list of items. In this approach programmer have to create item class which inherits from TCollectionItem and set this newly created class type to TCollection constructor parameter.


Example units

See also

External links