I want to create a tagged type inside a package that describes a 2D discrete space, with a size determined in running time. (context : implementation of a game of life)
First way I found was genericity :
generic
Size : Natural;
package Worlds is
type World_Type is tagged private;
type World is access World_Type'Class;
subtype Coordinate is Positive range 1..Size;
private
type World_Array is array (Coordinate, Coordinate) of Boolean;
type World_Type is tagged record
Content : World_Array;
end record;
end Worlds;
But, when implementing a visitor for worlds, genericity become a big problem :
with Worlds;
package World_Visitors is
type World_Visitor_Type is tagged private;
type World_Visitor is access World_Visitor_Type'Class;
procedure Visite(v : World_Visitor_Type;
w : in out Worlds.World); -- ERROR: invalid prefix in selected component "Worlds"
private
type World_Visitor_Type is tagged null record;
end World_Visitors;
GNAT can't compile that, because Worlds is a generic package. Then, because I don't want to write a Visitor for each possible world size, I try the C++ way : declare the size as attribute in the tagged type.
package Worlds is
type World_Type is tagged private;
type World is access World_Type'Class;
subtype Coordinate is Positive range <>;
function Init(Size : Natural) return World; -- initialize Content attribute as an array of length (Size*Size)
private
type World_Array is array (Coordinate, Coordinate) of Boolean;
type World_Type is tagged record
Content : World_Array;
Size : Natural;
end record;
end Worlds;
And, expectedly, this doesn't work, because World_Array needs an explicit range for Coordinates. In fact, I have no idea how to create a running-time-choosen sized array in a tagged type. I got some ideas from here, here, here or here, but nothing seems to make sense in this case.
How does Ada implement objects with variable-sized array attribute?