A.Pissicat
A.Pissicat

Reputation: 3285

Convert type to string

I created a type :

packages MyTypes.Type_A is
    subtype Counter_Type is Integer range 0 .. 15;
    type Array_Counter_Type is record
        Counter_01 : Counter_Type ;
        Counter_02 : Counter_Type ;
        Counter_03 : Counter_Type ;
        Counter_04 : Counter_Type ;
    end record;
end MyTypes.Type_A;

I want to display my array like this

MyArray : Array_Counter_Type;
print ( MyTypes.Type_A.Array_Counter_Type'Image (MyArray));

But I have error :

prefix og "Image" attribute must be scalar type

How can I do ? And is it possible to "customize" the Image to concat the 4 counters splited with '-' ?

Upvotes: 3

Views: 1777

Answers (1)

DeeDee
DeeDee

Reputation: 5941

That’s not possible yet, but it will be in Ada 202x [AI12-0020-1]. Until then you will have to define a subprogram (e.g Image) and call it explicitly. See also this related question on SO.

Example using GNAT.Formatted_String:

main.adb

with Ada.Text_IO;
with GNAT.Formatted_String;

procedure Main is

   subtype Counter_Type is Integer range 0 .. 15;

   type Array_Counter_Type is
      record
         Counter_01 : Counter_Type;
         Counter_02 : Counter_Type;
         Counter_03 : Counter_Type;
         Counter_04 : Counter_Type;
      end record;

   -----------
   -- Image --
   -----------

   function Image (Array_Counter : Array_Counter_Type) return String is      
      use GNAT.Formatted_String;      
      Format : constant Formatted_String := +"%02d-%02d-%02d-%02d";
   begin      
      return
        -(Format
          & Array_Counter.Counter_01
          & Array_Counter.Counter_02
          & Array_Counter.Counter_03
          & Array_Counter.Counter_04);
   end Image;     

   AC : Array_Counter_Type := (0, 5, 10, 15);

begin
   Ada.Text_IO.Put_Line (Image (AC));
end Main;

But you could also use Ada.Integer_Text_IO, Counter_Type'Image, etc. instead if GNAT.Formatted_String is not available.

Upvotes: 5

Related Questions