Proteja el patrón CRTP del desbordamiento de la pila en llamadas "virtuales puras"
Considere el siguiente ejemplo estándar de CRTP:
#include <iostream>
template<class Derived>
struct Base {
void f() { static_cast<Derived *>(this)->f(); }
void g() { static_cast<Derived *>(this)->g(); }
};
struct Foo : public Base<Foo> {
void f() { std::cout << 42 << std::endl; }
};
int main() {
Foo foo;
foo.f(); // just OK
foo.g(); // this will stack overflow and segfault
}
Si esto fuera una herencia virtual regular, podría haber marcado virtualf
yg
métodos tan puros como
struct Base {
virtual void f() = 0;
virtual void g() = 0;
};
y obtener un error de tiempo de compilación sobreFoo
siendo abstracto Pero CRTP no ofrece tal protección. ¿Puedo implementarlo de alguna manera? La verificación del tiempo de ejecución también es aceptable. Pensé en compararthis->f
puntero constatic_cast<Derived *>(this)->f
, pero no logró hacerlo funcionar.