Check the class of objects

janderson askme at me.com
Thu Jun 5 08:44:35 PDT 2008


janderson wrote:
> Mael wrote:
>> Hello,
>>
>> another newb question ! I'm trying to design a large image library,
>> that should be usable enough for students to learn it quickly, but
>> powerful enough to be used in medium-sized projects
>>
>> Since I'm building several image classes (depending on the
>> characteristics of the image, such as grey / color, byte / float,
>> etc), I can either include a flag in each image that tells its class
>> ("I'm a color-byte image", "I'm a grey-byte image", etc.), or use
>> many if( cast(ColorByteImage)img !is null ) { doactionColorByte ; }
>> to check the type. What would be the most efficient way to test the
>> type of the class ? How is the cast(Class)v construct implemented in
>> the compiler (I guess there's some equivalent of a "i'm a color-byte
>> image" flag in the class structure) ?
> 
> I don't like either approaches.  RTTI should be looked at with a 
> suspicions eye in my opinion (ie has its uses but the this is not one of 
> them).  Efficiency wise, dynamic casts can be slow depending on how the 
> compiler implements them it may need to traverse each item in the tree. 
>  So the deeper the tree (another thing you should avoid) the worse the 
> performance.  enum/flag compares are pretty efficient (as long as they 
> aren't strings).
> 
> Polymorphism's bread and butter is this type of problem.  Virtual 
> lookups aren't that much worse when compared to enum flag.  Its 2 memory 
> lookups and 1 jump.  Look at the surrounding code around the virtual, 
> how much work is that doing comparatively?  Probably a whole lot more. I 
> wouldn't prematurely optimize this sort of thing.

BTW: let me clarify what I mean by polymorphism.  I'm not talking about 
the class return from a function its type like

bool isGray();

That's almost RTTI.  No, what I mean is moving the code that does stuff 
on isGray() into the image class, if it makes sense.

Note, depending on what your doing it may be better to use a flag, or 
"is function" instead of polymorphism but I'd need an example.

-Joel


More information about the Digitalmars-d-learn mailing list