开发者

Type conversion in ada

I have a package where I convert a string to an integer with this :

param: integer;
begin
param:= Integer'Value(param_string);

My question is verysimple, i would like to do the same thing, but with a generic package. The generic type is TypeElement. However i can't do this :

param: Typ开发者_如何学运维eElement;
begin
param:= TypeElement'Value(param_string);

The error is 'prefix of "value" attribute must be scalar type'

Is there a trick ?


The generic formal type you provide for TypeElement must represent a scalar type.

If you're declaring it as private, e.g.:

generic
   type TypeElement is private;

then that's not going to work, because there's no guarantee that TypeElement is going to be a scalar type, which, as you've discovered is required to use the 'Value attribute. You need to use one of the generic formal type representations for discrete types, as listed in the Ada LRM 12.5.2.

For example:

generic

   type Type_Element_Discrete is (<>);
   type Type_Element_Signed_Int is range <>;
   type Type_Element_Mod is mod <>;
   type Type_Element_Digits is digits <>;
   type Type_Element_Delta is delta <>;
   type Type_Element_Delta_Digits is delta <> digits <>;

package Gen_Convert is

   function Gen_Convert (Param_String : String) return Type_Element_Discrete;
   function Gen_Convert (Param_String : String) return Type_Element_Signed_Int;
   function Gen_Convert (Param_String : String) return Type_Element_Mod;
   function Gen_Convert (Param_String : String) return Type_Element_Digits;
   function Gen_Convert (Param_String : String) return Type_Element_Delta;
   function Gen_Convert (Param_String : String) return Type_Element_Delta_Digits;

end Gen_Convert;

Specifying the appropriate formal type also ensures that the instantiator of the generic provides a valid type. Here's the corresponding body demonstrating the 'Value conversions:

package body Gen_Convert is

   function Gen_Convert (Param_String : String) return Type_Element_Discrete is
   begin
      return Type_Element_Discrete'Value(Param_String);
   end Gen_Convert;

   function Gen_Convert (Param_String : String) return Type_Element_Signed_Int is
   begin
      return Type_Element_Signed_Int'Value(Param_String);
   end Gen_Convert;

   function Gen_Convert (Param_String : String) return Type_Element_Mod is
   begin
      return Type_Element_Mod'Value(Param_String);
   end Gen_Convert;

   function Gen_Convert (Param_String : String) return Type_Element_Digits is
   begin
      return Type_Element_Digits'Value(Param_String);
   end Gen_Convert;

   function Gen_Convert (Param_String : String) return Type_Element_Delta is
   begin
      return Type_Element_Delta'Value(Param_String);
   end Gen_Convert;

   function Gen_Convert (Param_String : String) return Type_Element_Delta_Digits is
   begin
      return Type_Element_Delta_Digits'Value(Param_String);
   end Gen_Convert;

end Gen_Convert;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜