问题描述
我正在尝试创建一个抽象方法来克隆从 base 派生的类并将它们作为 shared_ptr 返回,如下所示:
class Base {
public:
virtual std::shared_ptr<BaseSymbol> clone() = 0;
};
class Derived : public Base {
public:
Derived(const Derived& derived);
std::shared_ptr<Derived> clone();
};
这给我带来了编译错误。我知道这可以用普通指针来实现,那么我怎样才能让它与共享指针一起工作?
解决方法
协方差只能通过指针/引用实现。
对于智能指针,你必须“复制”界面:
class Base {
public:
std::shared_ptr<Base> clone() const
{
return std::shared_ptr<Base>(vclone());
}
virtual ~Base() = default;
protected:
virtual BaseSymbol* vclone() const = 0;
};
class Derived : public Base {
public:
Derived(const Derived& derived);
std::shared_ptr<Derived> clone() const
{
return std::shared_ptr<Derived>(vclone());
}
protected:
Derived* vclone() const override { return new Derived(*this); }
};
CRTP 可能有助于避免重写相同的模式。