【问题标题】:Ada Generic Type Image AttributeAda 通用类型图像属性
【发布时间】:2018-01-20 18:16:48
【问题描述】:

我目前正在大学的实时编程语言课程中学习 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 页面,但它还没有完成。

【问题讨论】:

  • 相关:stackoverflow.com/questions/13417337/… Ada 似乎没有办法将“任何标量类型”指定给泛型。 “任何 DISCRETE 类型……是的……type Item_Type_t is (<>); ,但对于固定类型和浮动类型,您只能自己处理。

标签: generics ada


【解决方案1】:

一种可能的解决方法(请原谅我的资本重组,这是我的编辑器的设置方式):提供 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);

【讨论】:

    【解决方案2】:

    除了询问如何做到这一点(上面已回答)之外,您似乎还想知道为什么它会以这种方式工作。泛型形式类型

    type Item_Type_T is private;
    

    可以用任何具有赋值和“=”的实际类型来实例化。这涵盖了多种类型,并非所有类型都是标量。对于所有可能的实际类型,泛型必须是合法的。由于 'Image 对于某些可能的实际类型是不合法的,因此您不能在泛型中将其用于此类型。

    【讨论】:

    • 感谢您的澄清。很难找到简单的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多