在 Ada 中将空枚举传递给泛型的惯用方法

Idiomatic Way to Pass an Empty Enumeration to a Generic in Ada

我正在实例化一个带有枚举的通用包,以访问多个值之一并在子程序重载中使用。我想要一个定义明确、编译时检查的值集,我可以使用和查找。

generic
    -- Different types because we don't want to ensure we never put
    -- beer in a wine class, or wine in a beer stein.  Our inventory
    -- never changes, for... reasons.
    type Wine is (<>);
    type Beer is (<>);
package Bar is
    type Wine_Glass is null record;
    type Beer_Stein is null record;

    -- Unopened cases/bottles of each.
    type Wine_Inventory is array (Wine) of Natural;
    type Beer_Inventory is array (Beer) of Natural;

    procedure Pour (G : in out Wine_Glass; W : in Wine);
    procedure Pour (S : in out Beer_Stein; B : in Beer);
end Bar;

描述空枚举的惯用语是什么?

with Bar;
procedure Wine_Tasting is
    type Sampling_Wine is (Tempranillo, Zinfandel, Merlot);
    pragma Unreferenced (Tempranillo, Zinfandel, Merlot);

    type No_Beer is (None);
    package Wine_Tasting_Bar is new Bar(Wine => Sampling_Wine, Beer => No_Beer);
    Stein : Wine_Tasting_Bar.Beer_Stein;
begin
    Wine_Tasting_Bar.Pour (Stein, None); -- legal!
end Wine_Tasting;

有没有一种方法可以描述 Beer 是一个没有值的枚举,这样 Pour 就永远不能用 Beer 调用?

根据 Ada 参考手册第 3.5.1 节,枚举类型被描述为

enumeration_type_definition ::= (enumeration_literal_specification {, enumeration_literal_specification})

前 enumeration_literal_specification 是必需的,后面的 enumeration_literal_specification 是可选的。从这个语法描述中我断言没有办法声明没有 enumeration_literal_specifications.

的枚举类型

您必须声明一个至少有两个值的枚举类型,然后声明一个没有值的子类型。您使用子类型实例化泛型:

type Wine_Kind is (Red, White, Green);
type Beer_Base is (Ale, Lager);
subtype No_Beer is Beer_Base range Lager .. Ale;

package Wine_Bar is new Bar (Wine => Wine_Kind, Beer => No_Beer);