Ada 如何强制类型保持为一组固定的非连续值?
当我将其作为有效的刻度值输入3时,我希望该程序会出现错误,但没有这样的运气:Ada 如何强制类型保持为一组固定的非连续值?,ada,static-predicate,dynamic-predicate,Ada,Static Predicate,Dynamic Predicate,当我将其作为有效的刻度值输入3时,我希望该程序会出现错误,但没有这样的运气: with Ada.Text_IO; use Ada.Text_IO; procedure predicate is type Scale is new Integer with Dynamic_Predicate => Scale in 1 | 2 | 4 | 8; GivesWarning : Scale := 3; -- gives warning begin Put_Line
with Ada.Text_IO; use Ada.Text_IO;
procedure predicate is
type Scale is new Integer
with Dynamic_Predicate => Scale in 1 | 2 | 4 | 8;
GivesWarning : Scale := 3; -- gives warning
begin
Put_Line ("Hello World");
loop
Put_Line ("Gimme a value");
declare
AnyValue : Integer := Integer'Value (Get_Line);
S : Scale := Scale (AnyValue); -- no check done!
begin
Put_Line ("okay, that works" & S'Image);
end;
end loop;
end predicate;
我找到了,但需要使用枚举,解决方案是从enum->value定义一个数组
我想要的东西至少在编译时给我一个警告,并允许我在运行时检查,如果我试图在其中放入无效值,则会引发错误。然后,如果我可以使用SPARK来证明不会出现无效值,我可以关闭上述检查。我的印象是静态/动态谓词就是这样工作的,所以上面的例子让我大吃一惊。您需要启用断言。使用
-gnata
编译或设置适当的断言\u策略
pragma Assertion_Policy(Dynamic_Predicate => Check);
然而,一些GNAT版本似乎忽略了断言_Policy pragma。但是-gnata有效。如果我在类型上使用静态谓词,它也适用于静态谓词。谢谢