In c++0x, there is a std::static_pointer_cast for std::shared_ptr, but there is no equivalent method for开发者_如何学JAVA std::weak_ptr. Is this intentional, or an oversight? If an oversight, how would I define an appropriate function?
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.
Howard's version is correct, but in many cases it makes sense to simply pass weakptr.lock() as parameter to std::static_pointer_cast:
std::weak_ptr<A> a = ...;
std::weak_ptr<B> b = std::static_pointer_cast<B>(a.lock());
This syntax explicitly shows what is going on, and makes code easy to read.
The omission is intentional because despite it's name, std::weak_ptr is not a pointer type and does not provide pointer interface (operator ->, operator *, static_pointer_cast, etc.).
精彩评论