comp.lang.ada
 help / color / mirror / Atom feed
From: Matthew Heaney <F22HEANEY@MASS.DNET.HAC.COM>
Subject: Another Way of Emulating printf
Date: Thu, 23 Mar 1995 13:56:31 -0800
Date: 1995-03-23T13:56:31-08:00	[thread overview]
Message-ID: <01HOH7KHCU0Y00OPZ6@EDEN1.HAC.COM> (raw)

In Magnus Kempe's most recent FAQ, I noticed an item (I think it had been
posted by Tucker Taft) that explained how to emulate C's printf function.
I've been thinking about it, and propose an alternate (though similar)
solution.

Tucker's idea was to have the print call take a single argument,
and overload "&" to build the argument:

   Print ("format spec" & A1 & A2);

Here is another way: separate the format specification from the arguments,
and make the type for the arguments an unconstrained array of a (private)
argument type.

Each scalar type would have its own generic function to convert to the
argument type.  I usually name the instantiation "+", to keep the Print
call as simple as possible. (I copped this idea from Barnes, who used it
to hide allocator calls to make a ragged array.)

package Message_Handler is

   type Argument is private;

   type Arguments is array (Positive range <>) of Argument;

   generic
      type Item is (<>);
   function From_Discrete (The_Item : Item) return Argument;

   -- generic
   --    type Item is digits <>;
   -- function From_Floating_Point ...

   -- generic
   --    type Item is delta <>;
   -- function From_Fixed_Point ...

   function "+" (The_Item : String) return Argument;

   procedure Print (
      The_Format    : in String;
      The_Arguments : in Arguments);

private

   Max_Length : constant := 132; -- arbitrary upper bound

   -- There are probably other ways of implementing type Argument.
   --
   type Argument is
      record
         The_Image  : String (1..Max_Length);
         The_Length : Natural := 0;
      end record;

end Message_Handler;


with Message_Handler; use Message_Handler;

procedure Test_Formatted_Print is
   function "+" is new From_Discrete (Integer);

   type Color is (Red, Green, Blue);
   function "+" is new From_Discrete (Color);

   I : Integer := 5;
   C : Color := Blue;
begin
   Print ("format options here", (+I, +"hello", +C) );
end Test_Formatted_Print;


Hope this helps!

Matt
f22heaney@mass.dnet.hac.com



                 reply	other threads:[~1995-03-23 21:56 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox