shared_ptr feature request: void_pointer_cast

I know this isn't the best time to request a new feature, but I just had an idea for an extremely useful new function for shared_ptr. It is common to use a shared_ptr<void> in places where a void * would otherwise be used. While a void * can point to anything, there is no safe way to determine at run-time what type it originally pointed to. Casting it to the wrong type can result in undefined behavior. Although there's no way to avoid this problem with a plain void *, except by passing type information along with it, it should be possible to improve on this situation for shared_ptr<void>, using the template function void_pointer_cast. template<class X> shared_ptr<X> void_pointer_cast(shared_ptr<void> pv); (and similarly for shared_ptr<const void>, shared_ptr<volatile void> and shared_ptr<const volatile void>) void_pointer_cast should have the following semantics: if (pv.get() && pv owns an object of type X) { return shared_pointer_cast<X>(pv); } else { return shared_ptr<X>(); } This would allow code like the following shared_ptr<void> pv = getNextObject(); if (shared_ptr<int> pInt = void_pointer_cast<int>(pv)) { // Do something with pInt; } else if (shared_ptr<string> pString = void_pointer_cast<string>(pv)) { // Do something with pString; } Note that while this code is very similar to code using dynamic_pointer_cast, void_pointer_cast would be usable even when the target type is not a class with virtual functions. On the other hand, given code like shared_ptr<void> pv(new Derived); shared_ptr<Base> pb = void_pointer_cast<Base>(pv); pb.get() would equal 0, even if Base were a public base class of Derived and had a virtual destructor. void_pointer_cast should be easy to implement, using the same techniques as were used in get_deleter, and I think it would be of great use to many programmers. Joe Gottman
participants (1)
-
Joe Gottman