Checking if an object inherits from class T

K

Koszalek Opalek

I am using objects of class T and objects of
other classes that inherit from T. Somewhere
in my code I need to check if an object is of
class T or of any other class that inherits
from T.

The following
if( ref $obj eq 'T' )
(obviously) works only for objects of class T but
not for objects blessed to other classes that
inherit from T.


I have come up with two solutions:

1) add the following method to T:
sub isT {};
and then check
if ( $obj->can( 'isT' )

This works except that it is two times slower
that checking the ref (i.e. if (ref $obj eq 'T'. )


2) add a field isT to the object in the constructor
and than check
if ( $obj->{isT} )
This is as fast as checking the ref but it looks
ugly and duplicates the field across all objects.


Is there a more elegant way that would be as fast
as checking the ref?


Koszalek
 
B

Ben Morrow

Quoth Christian Winter said:
You can use Class->isa() (see "perldoc UNIVERSAL"):

if( ref($obj)->isa('T') )
{
# class is T or inherits from it
}

*NO*. Use $obj->isa('T') directly, otherwise objects can't override it
if they need to.

Ben
 
B

brian d foy

Christian Winter said:
You can use Class->isa() (see "perldoc UNIVERSAL"):

if( ref($obj)->isa('T') )
{
# class is T or inherits from it
}

actaully, you want to do

if( eval { $obj->isa("T") } )

Call isa() directly on the object, and don't care too much about what
is actaully in $obj. If it's not an object, you just get back false,
which is still the right nswer to the question. :)
 
K

Koszalek Opalek

actaully, you want to do

   if( eval { $obj->isa("T") } )

Call isa() directly on the object, and don't care too much about what
is actaully in $obj. If it's not an object, you just get back false,
which is still the right nswer to the question. :)

I fixed my code and then bumped in this very problem
(i.e. Can't call method "isa" without a package or object
reference). I come to perl.misc and there is an answer
before I even asked the question :D.

K.
 
K

Koszalek Opalek

actaully, you want to do

if( eval { $obj->isa("T") } )

Call isa() directly on the object, and don't care too much about what
is actaully in $obj. If it's not an object, you just get back false,
which is still the right nswer to the question. :)

The only thing is that it is approximately 4x slower on my
simple benchmark compared to just checking the ref, i.e.
if( ref $obj eq 'T' )

But that's the way it has to stay.

K.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top