繁体   English   中英

Ada通用类型图像属性

[英]Ada Generic Type Image Attribute

我目前正在大学的实时编程语言课程中学习Ada,并对泛型有疑问。

我有一个通用程序csv_put

package PSU_Logging is

   type logged_signal_names_t is (
      t,
      U_V1,
      I_L1,
      U_C1,
      I_L2,
      U_C2,
      I_Load
   );

private
   ... Some types, tasks and subprogramms ...

   generic
      type Item_Type_t is private;
      procedure csv_put (File : in File_Type; Item : in Item_Type_t);

end PSU_Logging;

与定义

package body PSU_Logging is

   procedure csv_put (File : in File_Type; Item : in Item_Type_t) is
   begin
      Put (File, Item_Type_t'Image (Item));
      Put (File, ", ");
   end csv_put;

   procedure csv_put_float is new csv_put (Item_Type_t => Float);
   procedure csv_put_duration is new csv_put (Item_Type_t => Duration);
   procedure csv_put_signal_name is new csv_put (Item_Type_t => logged_signal_names_t);

   ... Definition of other things ...

end PSU_Logging;

到现在为止还挺好。 太糟糕了,编译期间出现以下错误

Compile
   [Ada]          psu_logging.adb
      psu_logging.adb:9:18: prefix of "image" attribute must be a scalar type or a scalar object name
gprbuild: *** compilation phase failed

有任何想法吗? 我以为我可以像其他任何类型一样在通用过程中使用通用类型。 由于我所有实例都使用标量类型,因此我认为这应该不是问题。

顺便说一句:您最喜欢的Ada教程/参考是什么? 我喜欢Ada上的Wikibooks页面,但尚未完成。

可能的解决方法(原谅我的注资,这是我的编辑器的设置方式):将Image作为通用参数提供,

generic
   type Item_Type_T is private;
   with function Image (Item : Item_Type_T) return String;
procedure Csv_Put (File : in File_Type; Item : in Item_Type_T);

procedure Csv_Put (File : in File_Type; Item : in Item_Type_T) is
begin
   Put (File, Image (Item));
   Put (File, ", ");
end Csv_Put;

并使用'Image如果可用)实例化,否则使用您自己的实例化:

procedure Csv_Put_Float is new Csv_Put (Item_Type_T => Float,
                                        Image => Float'Image);

除了询问上面已经回答过的方法之外,您似乎还想知道它为什么以这种方式起作用。 通用形式类型

type Item_Type_T is private;

可以使用具有赋值和“ =”的任何实际类型实例化。 它涵盖了各种各样的类型,但并非所有都是标量的。 对于所有可能的实际类型,泛型必须合法。 由于“对于某些可能的实际类型,图像不合法,因此不能在通用类型中将其用于此类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM