Following are some examples of how the previously presented tools can be used to perform several run-time operations:
A* pa = new B; //construct a B and reference it //via a base-class pointer B* pb = PTR_CAST(B,pa); //run-time cast the A* to a B*. //Will succeed since //pc is in fact pointing to a B if (pb) pb->b_method(); //check if cast ok, then call a method of B C* pc = PTR_CAST(C,pa); //cast the A* to a C*. Will fail since //pa is pointing to a B but not a C if (pc) pc->c_method(); //pc will be NULL, so nothing will be done
f(A* ptr) { cout<<"This pointer is of type<<STATIC_TYPE_NAME(A) <<"but actually points to a "<<TYPE_NAME(ptr)<<endl; }
Assuming ptr points to a C object and the RTTI information has been defined as in Section 4.2, the above code will print:
This pointer points is of type A but actually points to a C
typeid At = STATIC_TYPE_INFO(A); typeid Bt = STATIC_TYPE_INFO(B); typeid Ct = STATIC_TYPE_INFO(C); A* pa = new B; //construct a B and reference //it via a base-class pointer int cast_to_B = DYN_CAST(Bt,pa); //cast_to_B will be 1 //since pa is pointing to a int cast_to_C = DYN_CAST(Ct,pa); //cast_to_C will be 0 //since a B is not a C
typeid t = TYPE_INFO(pa); //get typeid of the pa pointer int cast_to_B = Bt.can_cast(t); //trying to cast t to //a Bt will return int cast_to_C = Ct.can_cast(t); //trying to cast t to //a Ct will return 0
char name[10]; cout<<"Give name of type to instantiate (subclass of BASE)"; cin>>name; //get a textual type name //from the user dyn_typeid t(name); //create a typeid for //the given type name BASE* obj = TYPE_NEW(BASE,t); //try to create an object //of type t
In the above example, we assume that the types the user wishes to instantiate are all derived from some base class BASE. The reasons the types supplied by the user have to be derived from a known type are described in Section 5.2.6.