comp.lang.ada
 help / color / mirror / Atom feed
From: Ludovic Brenta <ludovic.brenta@insalien.org>
Subject: Re: Base'Class is instance of Der1?
Date: Sat, 08 Jan 2005 13:51:00 +0100
Date: 2005-01-08T13:51:00+01:00	[thread overview]
Message-ID: <87llb4krt7.fsf@insalien.org> (raw)
In-Reply-To: 1105185677.254129.171840@c13g2000cwb.googlegroups.com

"R" writes:
> Hello.
>
> I've got function which has a parameter of type Base'Class.
>
> well I have 3 derived tagged records and depending of what exactly is
> the parameter I have to cast it to a proper function.
>
> How can I figure out whether or not given object is der1 or der2 or
> der3 type?
>
> thanks in advance
>
> best regards
> R

This is called "dispatching", and Ada 95 supports it directly in the
language.  There is no need for you to explicitly check the actual
type:

package P is
   type Base is tagged abstract null record;
   procedure Proc (B : in Base) is abstract;

   type Der1 is new Base with null record;
   procedure Proc (D : in Der1);

   type Der2 is new Base with null record;
   procedure Proc (D : in Der2);

   type Der3 is new Base with null record;
   procedure Proc (D : in Der3);
end P;

with P;
procedure Dispatch (B : in P.Base'Class) is
begin
   P.Proc (B); -- dispatches to the appropriate Proc
end Dispatch;

To make this work, you must make sure that each instance of Proc is a
"primitive operation" of the appropriate type.  A "primitive
operation" is:

- declared in the same package as the type
- has at least one parameter or return value of the type

Primitive operations are defined in detail in ARM 3.2.3.

And you have to make sure that the point where you call P.Proc is a
"dispatching call".  For the call to be dispatching, the actual
parameter must be of a class-wide type, here Base'Class.

The precise rules for dispatching calls are in ARM 3.9.2.

Now, if you really insist on checking the actual type yourself:

with P;
procedure Dispatch (B : in P.Base'Class) is
begin
   if B in P.Der1'Class then
      -- dispatch
   elsif B in P.Der2'Class then
      -- dispatch
   ...
end Dispatch;

This is much more error-prone and less maintainable than
language-assisted dispatching.  I do not recommend this way.

-- 
Ludovic Brenta.



  parent reply	other threads:[~2005-01-08 12:51 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2005-01-08 12:01 Base'Class is instance of Der1? R
2005-01-08 12:38 ` Martin Krischik
2005-01-08 14:25   ` Martin Dowie
2005-01-08 15:00     ` Martin Krischik
2005-01-10  9:29       ` Martin Dowie
2005-01-08 12:51 ` Ludovic Brenta [this message]
2005-01-08 14:20 ` Dreni
replies disabled

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