Check the class of objects
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jun 5 08:46:13 PDT 2008
"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) ?
The correct way is to use the if(cast(ColorByteImage)img) if you have a
single attribute you want to switch on. This is implemented in the compiler
as a check to make sure the class is of the valid type, and then return the
casted value if it is correct, or return null if it is not.
You can also get information about the most derived class at runtime using
the .classinfo property, but if you have a deep hierarchy, it is less code
to just do the cast test.
If you want to switch on multiple orthogonal attributes, it would be better
to provide properties in the class that indicate which ones are which. For
example, the properties grey/color and byte/float could be orthogonal
producing 4 different variations. If you only care if an image is grey or
color, it would be inefficient to do something like:
if(cast(ColorByteImage)img !is null || cast(ColorFloatImage)img !is null)
if you could just do:
if(img.isColor)
-Steve
More information about the Digitalmars-d-learn
mailing list