diff --git a/_posts/2024-09-02-CRTP-introduce.md b/_posts/2024-09-02-CRTP-introduce.md new file mode 100644 index 0000000..61e41ca --- /dev/null +++ b/_posts/2024-09-02-CRTP-introduce.md @@ -0,0 +1,59 @@ +--- +title: CRTP:使用笔记 +date: 2024-09-02 +0800 # 2022-01-01 13:14:15 +0800 只写日期也行;不写秒也行;这样也行 2022-03-09T00:55:42+08:00 +categories: [c++] +tags: [c++, template] # TAG names should always be lowercase + +# 以下默认false +math: true +mermaid: true +# pin: true +--- + +## 1. 动态继承运行时时间损耗 + +* 每个 virtual 方法,都需要通过指针查找到虚函数入口(间接寻址),且可能引起`I-Cache` `cache miss`; +* virtual 方法,不能被优化为`inline`,针对一些短小的函数,时间损耗较大; + +## 2. CRTP 使用举例:子类也是 template 模板类 + +```c++ +template +class HoleDetectorBase { + public: + using underlying_type = HoleDetectorBase; + //... +}; + +template +class HoleDetector2 : public HoleDetectorBase> { + public: + using base_t = HoleDetectorBase>; + using typename base_t::underlying_type; + + //... +}; +``` + +* 继承写法为:`HoleDetector2`,即带上template参数。 + +### 2.1 添加在基类中封装子类的函数 + +```c++ +template +class HoleDetectorBase { +//... + +DerivedT& underlying() { return static_cast(*this); } +DerivedT const& underlying() const { return static_cast(*this); } + +//... +}; +``` + +## 3. 参考资料 + +* [unique_ptr 与抽象类的多态](https://hedzr.com/c++/algorithm/unique_ptr-and-abstract-class/) +* [An Implementation Helper For The Curiously Recurring Template Pattern](https://www.fluentcpp.com/2017/05/19/crtp-helper/) +* [The Curiously Recurring Template Pattern in C++](https://eli.thegreenplace.net/2011/05/17/the-curiously-recurring-template-pattern-in-c/#id3) +* [The cost of dynamic (virtual calls) vs. static (CRTP) dispatch in C++](https://eli.thegreenplace.net/2013/12/05/the-cost-of-dynamic-virtual-calls-vs-static-crtp-dispatch-in-c)