質問

I have this CRTP with an incomplete child class that is missing a method that is "not really" implemented in the base class:

#include <iostream>

using namespace std;

template<class T>
class BaseA
{
  public:
  T& asChild(){return static_cast<T&>(*this);}
  void AMethod(void) {asChild().AMethod();}
};

class IncompleteChild : public BaseA<IncompleteChild>
{
  public:
  // uncomment the following to avoid segfault:
//    void AMethod(void) {cout << "IncompleteChild Method" << endl;}
};

class Child : public BaseA<Child>
{
  public:
  void AMethod(void) {cout << "Child AMethod" << endl;}
};

template<class T>
void printBaseA(BaseA<T>& a)
{
  a.AMethod();
}

int main()
{
  IncompleteChild cI;
  cI.AMethod();
  printBaseA(cI);

  return 0;
}

This compiles fine, but results in a segmentation fault at runtime. How can I avoid that? I'd prefer a compiler error here (using gcc 4.6.3).

役に立ちましたか?

解決

Since your class doesn't actually have a member AMethod, you end up calling the member of the CRTP base, which gives you infinite recursion.

The simple solution is not to reuse names all over the place, but have one called AMethod and the other AMethodImpl or something like that:

void AMethod()
{
    static_cast<T*>(this)->AMethodImpl();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top