There is an old hack to making semi-generic containers in Delphi using include-files.
See http://www.delphikingdom.com/asp/viewitem.asp?catalogid=453&mode=print and start with 3d listing to grasp the idea.
However having two inter-dependent INC-files in units' interface
and implementation
sections leads to troubles: seems like XE2 compiles those include files as independent units instead and implementation cannot find functions declared in interface. It does not happen every time, but i failed to determine the conditions and thus failed to make a workaround.
Trying to re-formulate this in Delphi generics unit with as little changes as possible (i had to move huge legacy project to XE2 and "working" should be 1st, optimizations and refactoring later), i stuck into the following pit:
TemplateList<_DATA_TYPE_> = class
public
const MaxListSize = Maxint div (sizeof(Integer)*sizeof(_DATA_TYPE_));
type
TIntList = array[0..MaxListSize - 1] of _DATA_TYPE_;
PIntList = ^TIntList;
private
FList: PIntList;
FCount: Integer;
This gives an error that Low-bound for TIntList
is upper than High-bound. Which, i think, means that const MaxListSize
is evaluated to zero, but the TIntType
tries to be evaluated immediately, not when actually instantiating the type.
I wonder if XE3 or XE4 fixed this. And if there is a way to make this compile in XE2 without major re-working
PS. making the array 0..0 and suppressing bounds checking is usual solution, yet it make a lot of fragile non-checked code. Maybe i'd end up using real TList
or TList<integer\>
instead...
PPS. Funny thing, reformulating inner type with copy-paste
TIntList = array[0..Maxint div (sizeof(Integer)*sizeof(_DATA_TYPE_)) - 1] of _DATA_TYPE_;
changes the error into "const expression required".
So the same expression is considered const-enough in one branch of compiler and non-const in another... I wonder if it constitutes an inconsistency bug per se.
0..0
and suppressing bounds checking is usual solution, yet it make a lot of fragile non-checked code I don't think so. In what way is that any more fragile than0..MaxPossibleIndex
? – David Heffernan