我有一个像下面这样的智能指针类:
template <class T>
class Sptr {
template<typename U> friend class Sptr;
template <typename T1, typename T2>
friend bool operator==(const Sptr<T1> &a, const Sptr<T2> &b);
private:
T* obj;//pointer to current obj
RC* ref; //reference counter
std::function<void()> destroyData;
bool ok_;
public:
Sptr();
~Sptr();
template <typename U>
Sptr(U *);
Sptr(const Sptr &);
template <typename U>
Sptr(const Sptr<U> &);
template <typename U>
Sptr<T> &operator=(const Sptr<U> &);
Sptr<T> &operator=(const Sptr<T> &);
void reset();
T* operator->() const
{return obj;};
T& operator*() const
{return *obj;};
T* get() const
{return obj;};
explicit operator bool() const {
return ok_;
}
};
到目前为止一切正常,我想为 and 编写static_pointer_cast
函数dynamic_pointer_cast
。我不知道如何继续前进。谁能指导我正确的方向。下面是一个示例测试代码,我打算通过它来测试它。(c++11 还可以)
// Test static_pointer_cast.
{
Sptr<Derived> sp(new Derived);
Sptr<Base1> sp2(sp);
Sptr<Derived> sp3(static_pointer_cast<Derived>(sp2));
}
// Test dynamic_pointer_cast.
{
Sptr<Derived_polymorphic> sp(new Derived_polymorphic);
Sptr<Base_polymorphic> sp2(sp);
Sptr<Derived_polymorphic> sp3(dynamic_pointer_cast<Derived_polymorphic>(sp2));
Sptr<Derived_polymorphic> sp4(static_pointer_cast<Derived_polymorphic>(sp2));
Sptr<Derived2_polymorphic> sp5(dynamic_pointer_cast<Derived2_polymorphic>(sp2));
assert(!sp5);
}