网站建设最新模板下载,文旅策划公司,html手机网站开发教程,清晰化网站设计模式种最熟知的是23种经典设计模式#xff0c;但奇异递归模板模式(Curiously Recurring Template Pattern, CRTP)是否有资格被单独当成一种设计模式#xff0c;但是在C种#xff0c;CRTP确实是一种模式。其理念非常简单#xff1a; 继承者将自身作为模板参数传递给基类…设计模式种最熟知的是23种经典设计模式但奇异递归模板模式(Curiously Recurring Template Pattern, CRTP)是否有资格被单独当成一种设计模式但是在C种CRTP确实是一种模式。其理念非常简单 继承者将自身作为模板参数传递给基类
struct Foo : BaseFoo
{...
}这么做的一个原因是可以在基类的实现中 访问特定类型 的this指针
假设积累Base的每个单一派生类均实现了迭代所需要的begin() end()接口那么如何在基类Base的内部而不是派生类的内部迭代对象直觉告诉我们不能这么做因为Base自身并没有提供begin() end() 接口。但是如果使用CRTP便可以将自身的信息传递给基类
struct MyClass : BaseMyClass
{class iterator{.....}iteretor begin() const {.....}iterator end() const {.....}
}So,这意味着我们在基类的内部可以将this指针转换为派生类的类型
template typename Derived
struct Base
{void foo(){for (auto item : *static_castDerived* (this)){//.....}}
};
当MyClass的某个实例调用foo接口时this指针将Base转为MyClass(下转型)。然后通过解引用这个指针并在range-based for loop中实现迭代通过调用MyClass::begin() MyClass::end()
后面有机会再多写点…