Search code examples
c++11weak-ptr

static_pointer_cast for weak_ptr


In c++0x, there is a std::static_pointer_cast for std::shared_ptr, but there is no equivalent method for std::weak_ptr. Is this intentional, or an oversight? If an oversight, how would I define an appropriate function?


Solution

  • This ought to do it for you:

    template<class T, class U>
    std::weak_ptr<T>
    static_pointer_cast(std::weak_ptr<U> const& r)
    {
        return std::static_pointer_cast<T>(std::shared_ptr<U>(r));
    }
    

    This will throw an exception if the weak_ptr has expired. If you would rather get a null weak_ptr, then use r.lock() instead.