This is using CRTP for static polymorphism, but without implementing a derived function. Compiles in both gcc and visual studio. What for?

#include <iostream>

template <class Derived>
class Base
{
public:
  void method1()
  {
    static_cast<Derived*>(this)->method1();
  }

  void method2()
  {
    static_cast<Derived*>(this)->method2();
  }
};

class Derived1: public Base<Derived1>
{
public:
  void method1()
  {
    std::cout << "Method 1 of Derived1 executed.\n";
  }
};

int main(int argc, char *argv[])
{
  Derived1 d1;
  d1.method1();
  d1.method2();
  return 0;
}

Next question: how to make this type safe? That is, if someone forgets to implement method2, I would like the compiler to catch it. I do not want this to explode at runtime.

+3
source share
2 answers

I think the reason is that it really is: if you instantiate this code:

void method2()
{
  static_cast<Derived*>(this)->method2();
}

where Derivedit has no implementation method2(), it will essentially be an illustrious self-recursive call. The reason is that there Derived1really exists a member function called method2, namely, inherited from the base class.

, , , method2 .

CRTP , , . , , . , .

+8
  Derived1 d1;
  d1.method2();

Derived1 method2(), , Base . . d1.method2() Base::method2(), . .

+2

Source: https://habr.com/ru/post/1786079/


All Articles