跳至主要内容

CRTP & 靜態多型

Introduction

  • Curiously Recurring Template Pattern
  • Static Polymorphism

CRTP

一種C++程式繼巧,須符合以下條件

  1. Derived class 必須繼承某個樣板類別
  2. 繼承時,該樣板類別要使用Derived class為parameter
template<typename T>
class Base{}


class Derived: public Base<Derived>
{

}

靜態多型

使用CRTP,當要implement一個member function時,在Base class使用static_cast<>把 this 轉成type T,再去呼叫member function。

  • Derived 用 Base class 宣告成 Base<Derived>的形式

靜態多型的關鍵在使用CRTP

靜態 v.s. 動態多型

  • 靜態多型可以在compile time就決定型別
  • 當需要依據使用者input決定型態時,必須要用動態多型,在runtime決定型別

Ref: