不是直接的,但是你可以通過使虛擬函數在類外部不可訪問並將虛擬函數調用包裝爲非虛函數來僞裝它。缺點是你必須記得在每個派生類上實現這個包裝函數。但是你可以通過把這個virtul函數聲明和包裝器放到宏中來解決這個問題。
using namespace boost; // for shared_ptr, make_shared and static_pointer_cast.
// "Fake" implementation of the clone() function.
#define CLONE(MyType) \
shared_ptr<MyType> clone() \
{ \
shared_ptr<Base> res = clone_impl(); \
assert(dynamic_cast<MyType*>(res.get()) != 0); \
return static_pointer_cast<MyType>(res); \
}
class Base
{
protected:
// The actual implementation of the clone() function.
virtual shared_ptr<Base> clone_impl() { return make_shared<Base>(*this); }
public:
// non-virtual shared_ptr<Base> clone();
CLONE(Base)
};
class Derived : public Base
{
protected:
virtual shared_ptr<Base> clone_impl() { return make_shared<Derived>(*this); }
public:
// non-virtual shared_ptr<Derived> clone();
CLONE(Derived)
};
int main()
{
shared_ptr<Derived> p = make_shared<Derived>();
shared_ptr<Derived> clone = p->clone();
return 0;
}
http://stackoverflow.com/questions/196733/how-can-i-use-covariant-return-types-with-smart-pointers – 2010-04-22 02:12:37