给定以下程序:
#include <memory>
template <typename T>
class SharedPtr : public std::shared_ptr<T>
{
typedef std::shared_ptr<T> Impl;
template<typename U> friend class SharedPtr;
SharedPtr( Impl const& other ) : Impl( other ) {}
public:
SharedPtr( T* newed_ptr ) : Impl( newed_ptr ) {}
SharedPtr( SharedPtr const& other ) throw() : Impl( other ) {}
template <typename U> SharedPtr( SharedPtr<U> const& other ) throw() : Impl( other ) {}
template <typename U> SharedPtr<U> DynamicCast() const throw()
{
return SharedPtr<U>( std::dynamic_pointer_cast<U>( *this ) );
}
};
template<typename T> class Handle : public SharedPtr<T const>
{
typedef SharedPtr<T const> Base;
template <typename U> friend class Handle;
public:
explicit Handle( T const* pObject = 0 ) : Base( pObject ) {}
Handle( SharedPtr<T> const& src ) : Base( src ) {}
template <typename Derived>
Handle( Handle<Derived> const& other ) : Base( other ) {}
template <typename Derived>
Handle<Derived> DynamicCast() const throw() {
SharedPtr<Derived const> tmp = this->Base::template DynamicCast<Derived const>();
return Handle<Derived>( tmp );
}
};
class B { public: virtual ~B() {} };
class D : public B{};
void
testit()
{
Handle<D> p( new D );
Handle<B> p1( p );
Handle<D> p2( p1.DynamicCast<D>() );
}
我收到以下错误(来自 g++ 4.7.2):
noX.cc: In instantiation of ‘SharedPtr<T>::SharedPtr(const SharedPtr<U>&) [with U = const D; T = D]’:
noX.cc|33 col 37| required from ‘Handle<Derived> Handle<T>::DynamicCast() const [with Derived = D; T = B]’
noX.cc|45 col 37| required from here
noX.cc|13 col 88| error: no matching function for call to ‘std::shared_ptr<D>::shared_ptr(const SharedPtr<const D>&)’
noX.cc|13 col 88| note: candidates are:
和一长串候选人。Microsoft (MSVC 11) 给出了类似的消息,所以我假设错误在我的代码中,而不是编译器错误。
显然,我不希望能够将 a 转换SharedPtr<D const>
为 a SharedPtr<D>
(或 astd::shared_ptr<D const>
到 a std::shared_ptr<D>
,这是微软所抱怨的)。但是
SharedPtr<D>
首先从哪里来?我在上面的代码中看不到任何应该创建任何类型的非 const 智能指针的东西。