今天学了一个新的C++知识点,诚然life is too short to learn c++.

先看cpprefernece上的表述, https://en.cppreference.com/w/cpp/language/crtp

可见,通过这种奇怪的方式,可以在编译期实现多态。从而省去了虚函数的调用开销(查虚表)以及虚指针的内存开销。追求极致性能可以考虑使用这种技巧。

简单来说,就是这样使用:

#include <cstdio>
 
template <class Derived>
class Base {
public:
    void interface() {
        static_cast<Derived*>(this)->impl();
    }
};
 
class D1 : public Base<D1> {
public:
    void impl() {
        printf("hello from D1\n");
    }
};
 
class D2 : public Base<D2> {
public:
    void impl() {
        printf("hello from D2\n");
    }
};
 
int
main(int argc, const char* argv[])
{
    D1 d1;
    D2 d2;
    d1.interface();
    d2.interface();
    return 0;
}
 
// output:
// hello from D1
// hello from D2

更详细的参考:https://xr1s.me/2022/10/18/brief-introduction-to-crtp/

别称:静态绑定,静态多态

see also 多态