奇异递归模板模式
// g++ --std=c++17 -Wall main.cpp #include <algorithm> #include <iostream> // 1: Curiously Recurring Template Pattern(CRTP)奇异递归模板模式 // 静态多态,像虚函数一样调用派生类的函数,但不需要 virtual,性能更好(编译期解析)。 // 还需要多思考一下,感觉还有点迷惑 namespace CRTP { template <typename Derived> class backend_ctx { public: void common_logic() { static_cast<Derived*>(this)->do_something(); } }; class stream_ctx : public backend_ctx<stream_ctx> { public: void do_something() { std::cout << "stream_ctx doing something!\n"; } }; inline void test() { stream_ctx ctx; ctx.common_logic(); // 输出: stream_ctx doing something! } } // namesapce CRTP int main() { CRTP::test(); return 0; }