comp.lang.ada
 help / color / mirror / Atom feed
* Another Way of Emulating printf
@ 1995-03-23 21:56 Matthew Heaney
  0 siblings, 0 replies; only message in thread
From: Matthew Heaney @ 1995-03-23 21:56 UTC (permalink / 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



^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~1995-03-23 21:56 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
1995-03-23 21:56 Another Way of Emulating printf Matthew Heaney

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