Show: Object Pascal C++
Display Preferences

Overloads and Type Compatibility in Generics

From Appmethod Topics
Jump to: navigation, search

Go Up to Generics Index


Generic methods can participate in overloading alongside non-generic methods by using the 'overload' directive. If overload selection between a generic method and a non-generic method would otherwise be ambiguous, the compiler selects the non-generic method.

For example:

   TFoo = class
     procedure Proc<T>(A: T); overload;
     procedure Proc(A: String); overload;
     procedure Test;
 procedure TFoo.Test;
   Proc('Hello'); // calls Proc(A: String);
   Proc<String>('Hello'); // calls Proc<T>(A: T);

Type Compatibility

Two non-instantiated generics are considered assignment compatible only if they are identical or are aliases to a common type.

Two instantiated generics are considered assignment compatible if the base types are identical (or are aliases to a common type) and the type arguments are identical.

Note: Generics in Object Pascal are unlike templates in C++ or generic types in C#. Most notably, a type parameter cannot be constrained to a specific simple type, such as Integer, Double, String, and so forth. In cases where different types need to be expressed (including simple types), consider using overloaded functions for each needed type or use a record type such as TValue from the System.Rtti unit, which offers operators and methods for storing and querying these data types.

See Also

Personal tools
In other languages