What's the point of IsA() in C++?

前端 未结 5 1276
鱼传尺愫
鱼传尺愫 2021-02-10 16:14

I\'m trying to figure out why some code bases use IsA() to determine object polymorphism if in C++ you can already safely upcast and down cast (using dynamic_cast) ?

So

5条回答
  •  轮回少年
    2021-02-10 17:17

    Sometimes you dont have RTTI ( maybe you're working on a memory/cpu constrained system and disabling RTTI is the mandated solution) In that case you don't have dynamic_cast available to you. If you want to use something similar to RTTI you usually end up with solutions that are IsA() with static_cast.

    Another possible use for an IsA() function is when you don't know all your classes at compile-time (maybe they've been loaded from shared library), or you dont want to list all the types explicitly. This lets you write things like

    handleInstance( Instance * i )
    {
      //libs has been filled through loading dynamic libraries.
      for( auto it = libs.begin() ; it!=libs.end() ; ++it )
      {
         if( i->IsA( it->type_key ) )
         {
            it->process( i );
         }
      }
    }
    

    Though in this case I might turn the test condition inside out like

    if( it->can_process( i ) )
    

    and can_process would be free to use dynamic_cast.

提交回复
热议问题