kuangyu0801 / design-pattern-cpp

Practice design pattern in modern C++.
0 stars 0 forks source link

C++ 的靜態多型:CRTP #38

Open kuangyu0801 opened 2 months ago

kuangyu0801 commented 2 months ago
kuangyu0801 commented 2 months ago
template <class T>
class Base
{
public:
  void interface()
  {
    static_cast<T*>(this)->implementation();
  }

private:
  Base() = default;
  friend T;
//  ...
};

class Derived : public Base<Derived> {
public:
  void implementation() {}

};

Pro: Compile time, not dynamic dispatch via Vtable and Vpointer Con: The derived class of CRTP type is not of the same type. They don't actually inherit the same base class