C++ 使用接口和默认实现继承

C++ Inheritance with Interface and Default Implementation

本文关键字:默认 实现 继承 接口 C++      更新时间:2023-10-16

我不确定该怎么称呼这种继承方案,但我正在尝试使用具有默认实现的cloneable接口。不过,我在获得正确的方案时遇到了一些问题。

我在某种程度上基于 C# 中定义的可克隆接口。

首先,我有我的界面和默认实现:

template<class BaseType>
class ICloneable
{
public:
virtual std::shared_ptr<BaseType> Clone() const = 0;
};
template<class BaseType, class DerivedType>
class Cloneable : public ICloneable<BaseType>
{
public:
virtual std::shared_ptr<BaseType> Clone() const
{
return std::shared_ptr<BaseType>(new DerivedType(*(DerivedType*)this));
}
};

我的愿望是有以下方案。

// A pure virtual base interface
class Base : public ICloneable<Base>
{
public:
virtual void SomeFunc() = 0;
}
// Another implementation
class Imp1 : public Base, Cloneable<Base, Imp1>
{
public:
virtual void SomeFunc() {}
}
// An implementation
class Imp2 : public Cloneable<Base, Imp2>
{
public:
virtual void SomeFunc() {}
}

如果我有一个"std::shared_ptr"对象列表,我可以在想要制作深度副本时调用 Clone 函数,而无需在每个实现中手动编写函数。

现在我明白 Imp 是一个抽象类,这并不让我感到惊讶。有人知道我如何让这个默认实现想法起作用吗?关键是不必为每个实现手动编写克隆函数。这可能不可行,但我没有想法可以尝试。

您可以执行以下操作:

#include <memory>
template<typename InterfaceType_>
struct ICloneable
{
using InterfaceType = InterfaceType_;
virtual ~ICloneable() = default;
virtual std::shared_ptr<InterfaceType> clone() const = 0;
};
template<typename T, typename Base = ICloneable<T>>
struct CloneableMixin : public Base
{
using InterfaceType = typename Base::InterfaceType;
// With the following line uncommented, code does not compile in MSVC
//using typename Base::InterfaceType;
std::shared_ptr<InterfaceType> clone() const override
{ return std::make_shared<T>(*static_cast<const T*>(this)); }
};

现在,这可以按如下方式使用:

struct SomeBaseClass : public CloneableMixin<SomeBaseClass> { /*...*/ };
struct SomeDerivedClass : public CloneableMixin<SomeDerivedClass, SomeBaseClass> { /*...*/ };

两个注意事项:

  • 为了能够访问ICloneable的模板参数InterfaceType_您需要将其设置为模板别名,然后使用using typename Base::InterfaceType(因为它是模板参数依赖类型(。

  • 我已经为CloneableMixinBase模板参数提供了默认类型 - 这允许将其用于您希望实现clone基类。

此外,两个不相关的评论:

  • 您不需要键入virtual- 这是隐含的。最好在末尾添加override(这样可以确保该方法实际覆盖某些内容,否则编译器将报告错误(。

  • 您可以考虑使用std::make_shared而不是new