c++ - dynamic_cast to the same type does not check type of object -
i trying determine whether object pointed t* pointer t object, or other, unrelated type. tried dynamic_cast, less useless, returns pointer instead of null when obvious not point valid t object:
object* garbage = reinterpret_cast<object*>(0x12345678); if( dynamic_cast<object*>(garbage) == null ){ cout << "expected behaviour (by me)" << endl; }else{ cout << "you've got kidding me" << endl; }
is there workaround this, or other solution? i've tried casting void* , char* before dynamic_cast no avail, typeid not enough either since want accept subclasses well.
some context: i'm writing custom array class implementing shallow conversion between different kinds of arrays, array<object*>
, array<string*>
, , guarantee minimal type safety doing dynamic type check @ every element access, example:
#define debug array<string*> v(10); array<object*> o = v; o[0] = new integer(1); // technically illegal no idea how check //array<string*> w = o; // fails exception string* str = v[0]; // should fail horribly cout << str << endl;
casting object*, doing type check on object* works in lot of cases, fails in case of array<object*>
, though not sure whether possible insert non-object array<object*>
without use of reinterpret_cast.
base on example, sounds you've got shallow copy arrays trick containing different types supposed contain. think "normal" solution problem make difficult users (i.e. don't provide conversions between array<t>
, array<u>
). but, if you're set in ideas think work:
template<typename subclass> class array { public: // ... subclass *operator [] (size_t index) { assert( index < size_ ); assert( dynamic_cast<subclass*>(static_cast<object*>(internal_[index])) != null ); // ... } // ... private: size_t size_; subclass **internal_; };
you can template meta-magic , static assert make sure subclass
subclass of object
(exactly how different topic). once out of way, casting down object* , subclass
dynamic_cast should accomplish goal.
Comments
Post a Comment