Check the class of objects

Steven Schveighoffer schveiguy at yahoo.com
Thu Jun 5 09:35:56 PDT 2008


"Mael" wrote
> Well, most of the time, the check won't occur a big penalty, because, 
> first the image hierarchy will be small, and second, the pattern of use 
> will be like :
>
> algorithmprocess(Type)(args)
> {
> static switch(Type) dostuff ;
> }
>
> algorithm(args)
> {
> if( isByteImage(img) ) algorithmprocess(ByteImage)(cast(ByteImage)img) ;
> ...
> }
>
> which is a bit ugly but should work.. except I can't make it work :
>
> I did something like
>
> _myalgo( T )( T u )
> {
> static if (T == ByteImage) { do something ; }
> else static if( T == FloatImage) { ..; }
> }
>
> myalgo( Image u )
> {
> if( isByteImage(u) ) _myalgo( ByteImage )(cast(ByteImage)u) ;
> ...
> }
>
>
> and I obtain something like
> Error: cannot evaluate opEquals(cast(Object)(ByteImage)) at compile time
> (refering to the line "static if( T == ByteImage ) .."
>
> someone knows what is the correct way to check for the arg types?

Static if can only inspect compile-time objects.  This will not look up the 
derived type.

If you did want static if to work, you need to use an is expression. 
Something like:

static if(is(T == ByteImage))

But you are unnecessarily distributing your code, adding unnecessary 
templates, making it harder to understand/maintain

What's wrong with:

if(isByteImage(u))
{ do something; }
...

Either way, you still need the if-else block to determine what the image is 
at runtime.

-Steve 




More information about the Digitalmars-d-learn mailing list