Ada 自定义图像

Ada customise Image

有我喜欢的类型:

type T_MyType is (test1,
                  test2,
                  test3)

我想自定义 T_MyType'Image (..) 以显示类似这样的内容

-- !!! Not working code !!!
when test1 => "String1";
when test2 => "String2";
when test3 => "Other String"; -- Not the same length

我该怎么办?

如果您的编译器支持draft Ada 2022 standard ARM 4.10,这应该是可能的; GNAT CE 2021 有,FSF GCC 11.1.0 没有。

对于类型 T,您需要创建一个符合规范

的过程
procedure Put_Image
   (Buffer : in out 
      Ada.Strings.Text_Buffers.Root_Buffer_Type'Class;
    Arg   : in T);

参见 A4.12,通用文本缓冲区;并使用开关 -gnat2020.

进行编译

例如(不情愿地接受你多余的类型名称),

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Text_Buffers;

procedure Imaging is

   type T_MyType is (Test1,
                     Test2,
                     Test3);
   
   --  We have to see the procedure's spec ...
   procedure My_Image
     (Buffer : in out Ada.Strings.Text_Buffers.Root_Buffer_Type'Class;
      Arg    : in     T_MyType);

   --  ... so as to use it as a representation item ...
   for T_MyType'Put_Image use My_Image;
   
   --  ... before the compiler sees the body
   procedure My_Image
     (Buffer : in out Ada.Strings.Text_Buffers.Root_Buffer_Type'Class;
      Arg    : in     T_MyType)
   is
   begin
      Buffer.Put (case Arg is
                     when Test1 => "String1",
                     when Test2 => "String2",
                     when Test3 => "Other String");
   end My_Image;

begin
   for V in T_MyType loop
      Put_Line (V'Image);
   end loop;
end Imaging;

我通常定义一个图像函数,而不依赖于新的 Ada 2022 功能:

function Image (Item : T_MyType) return String
is begin
   case Item is
   when test1 => return "String1";
   when test2 => return "String2";
   when test3 => return "Other String";
   end case;
end Image;