#include <stlsoft/conversion/ptr_cast.hpp>
Assume the following class hierarchy, and variables:
class Parent { public: virtual ~Parent(); }; class A : public Parent { public: ~A(); }; class B : public Parent { public: ~B(); }; . . . A a; B b;
The following code segments illustrate the similarities and differences between dynamic_cast and ptr_cast:
(i) dynamic cast of reference that succeeds
A &ra1 = dynamic_cast<A&>(a); A &ra2 = stlsoft::ptr_cast<A&>(a); assert(&ra1 == &ra2);
(ii) dynamic cast of pointer that succeeds
A *pa = dynamic_cast<A*>(&a); assert(NULL != pa); assert(stlsoft::ptr_cast<A*>(&a) == pa);
(iii) dynamic cast of reference that fails
bool bCastFailed1 = false; try { B &b1 = dynamic_cast<B&>(a); . . . // Will never get here } catch(std::bad_cast &) { bCastFailed1 = true; } assert(bCastFailed1); bool bCastFailed2 = false; try { B &rb = stlsoft::ptr_cast<B&>(a); . . . // Will never get here } catch(std::bad_cast &) { bCastFailed2 = true; } assert(bCastFailed2);
(iv) dynamic cast of pointer that fails
assert(NULL == dynamic_cast<B*>(&a)); bool bCastFailed = false; try { B &rb = stlsoft::ptr_cast<B&>(&a); . . . // Will never get here } catch(std::bad_cast &) { bCastFailed = true; } assert(bCastFailed);
Public Types | |
typedef Target | target_type |
The target type. | |
typedef ptr_cast< Target > | class_type |
The current instantiation of the type. | |
typedef stlsoft::base_type_traits < Target >::cv_type | target_base_type |
The target base type. | |
typedef target_base_type & | reference_type |
The reference type. | |
typedef target_base_type * | pointer_type |
The pointer type. | |
Public Member Functions | |
template<typename Source> | |
ptr_cast (Source &s) | |
Constructor used when casting a reference. | |
template<typename Source> | |
ptr_cast (Source *s) | |
Constructor used when casting a pointer. | |
operator reference_type () const | |
Converts an instance of the cast class to a reference. | |
operator pointer_type () const | |
Converts an instance of the cast class to a pointer. |
typedef Target target_type |
The target type.
typedef ptr_cast<Target> class_type |
The current instantiation of the type.
typedef stlsoft::base_type_traits<Target>::cv_type target_base_type |
The target base type.
typedef target_base_type& reference_type |
The reference type.
typedef target_base_type* pointer_type |
The pointer type.
ptr_cast | ( | Source & | s | ) | [inline] |
Constructor used when casting a reference.
ptr_cast | ( | Source * | s | ) | [inline] |
operator reference_type | ( | ) | const [inline] |
Converts an instance of the cast class to a reference.
operator pointer_type | ( | ) | const [inline] |
Converts an instance of the cast class to a pointer.