跳轉到內容

更多 C++ 習語/引數化基類

來自 Wikibooks,開放世界中的開放書籍

引數化基類

[編輯 | 編輯原始碼]

將可重用模組中的某個方面抽象出來,並在需要時將其組合到給定型別中。

也稱為

[編輯 | 編輯原始碼]
  • 自下而上的混合
  • 引數化繼承

某個方面可以從需求中抽象出來,並作為模板開發(例如,物件序列化)。序列化是一個跨領域關注點,應用程式中的許多類/POD 型別可能具有此關注點。這種關注點可以在易於管理的可重用模組中抽象出來。透過新增一個方面,與原始型別的可替換性不會被破壞,因此另一個動機是與型別引數具有 IS-A(公有繼承)或 WAS-A(私有繼承)關係。

解決方案和示例程式碼

[編輯 | 編輯原始碼]
template <class T>
class Serializable : public T,   /// Parameterized Base Class Idiom
                     public ISerializable
{
  public:
    Serializable (const T &t = T()) : T(t) {}
    virtual int serialize (char *& buffer, size_t & buf_size) const
    {
        const size_t size = sizeof (T);
        if (size > buf_size)
          throw std::runtime_error("Insufficient memory!");

        memcpy (buffer, static_cast<const T *>(this), size);
        buffer += size;
        buf_size -= size;
        return size;
    }
};

Serializable <T> 可以多型地用作 T 以及 ISerializable。上面的示例僅在 T 是沒有指標的使用者定義的 POD 型別時才正常工作。

已知用途

[編輯 | 編輯原始碼]
[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書