Initializing a discriminated record
(If it matters, alr tells me that this is gnat_external=12.3.1
; notice the pragma)
I was recently in a situation along these lines:
pragma Ada_2022;
-- ...
type Enum is (A, B, C);
type Disc_Rec (Kind : Enum) is record
case Kind is
when A => Field : Natural;
when others => null;
end case;
end record;
-- ... in what follows, `Thing` is of type `constant Enum` and `Value` is of type
D : Disc_Rec := (
case Thing is
when A => Disc_Rec'(Kind => A, Field => Value),
when B | C => Disc_Rec'(Kind => Thing) -- LINE 37
);
gnat tells me:
test_enum.adb:37:48: error: no single variant is associated with all values of the subtype of discriminant value "Kind"
Column 47 lands on Thing
.
I understand the message, but Iβd have thought it clear that since Thing
has the type B
or C
in line 37, Thing
has all values of the subtype that matter in this branch. Indeed, if Disc_Rec
does not have the case
statement that defines Field
, and I remove the assignment to Field
in line 36, the compiler sings happily. So the problem doesnβt seem to be Thing
so much as that the optional Field
β¦ which isnβt needed in this branch.
Is there a way to make something like this work? My current workaround handles the branches explicitly (when A => ... , when B => ..., when C => ...
), but In a practical case, Kind
could have a lot of variants.
3 posts - 3 participants