[Insight-users] Re: Dynamic type checking

Luis Ibanez luis.ibanez at kitware.com
Wed Dec 29 11:45:36 EST 2004


Hi George,

Yes, this is actually a functionality provided by C++,
and it is known as RTTI (Run Time Type Information).

There are several ways to use it. In all cases, you need
to have an hypothesis of the type that you expect to find.
That is, RTTI will be able to tell you whether an object
is of type "T" or not. In all cases, you need to have a
pointer or a reference to the object.

Some of the methods are:

1) Attempt a dynamic cast to pointer to type T. If the
    resulting pointer is NULL, then... your object was not
    of type T:


     baseClassType  * p = GetObjectPointerSomeHow();

     derivedClassType * t =
         dynamic_cast< derivedClassType * >( p );

     if( t == NULL )
       {
       std::cout << "Sorry, this is not type T" << std::endl;
       }



2) Use the typeid() method. In this case you compare the
    typeid() of one type with the typeid() of another type.

     baseClassType  * p = GetObjectPointerSomeHow();

     if( typeid( p ) == typeid( derivedClassType * ) )
     {
     std::cout << "P is of type T" << std::endl;
     }


    Note that (1) and (2) are not fully equivalent,
    because in (2) you will get a "true" if one type
    derives from the other.



3) This last option is more for debugging purposes for
    printing out messages for humans. It shouldn't be used
    for comparison because it is not multi-platform.

      std::cout << typeid( p ).name() << std::endl;
      std::cout << typeid( derivedClassType * ).name() << std::endl;




In general you should use the method (1), which is what
you will see in most examples of Command/Observers.



    Regards,



       Luis



-------------------------------
Li, George (NIH/NCI) wrote:

> Luis:
> 
> Inside ITK, is there a dynamic type checking facility?
> For instance, I would like to know what optimizer or 
> metric type is at runtime. Is there a way to do this in
> ITK?
> 
> Thanks for your help,
> 
> George
> 
> 
> 






More information about the Insight-users mailing list