CRTP 指的是有個 class 繼承以它自己為 template 引數的 base
像這樣:
// The Curiously Recurring Template Pattern (CRTP)
template <typename t>
struct base
{
// ...
};
struct derived : base<derived>
{
// ...
};
這樣有什麼好處呢,其實是為了靜態多形(static polymorphism),
比如說 base class 定義介面然後去 call derived class 的 implement,
像這樣
template <class derived> struct Base
{
void interface()
{
// ...
static_cast<derived*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
Derived::static_sub_func();
// ...
}
};
struct Derived : Base<Derived>
{
void implementation();
static void static_sub_func();
};
上面的例子其實藉由介面轉發的手法規避了名稱衝突的問題,
然而這個 pattern 最奸巧的其實是即使名稱衝突也不用擔心 derived class 被 base class 遮蔽,
因為這在 compiling time 就會幫你選好,derived instance 一定只會用 derived function
管你用 base* 還是 derived* 去指都一樣
於是你就可以統一介面又不用付出 RTTI 的成本,有沒有很爽啊~
....其實好像也還好(跑
沒有留言:
張貼留言