CRTP编译,但我不喜欢.怎么样?

Chr*_*oph 1 c++ crtp

我有一个不完整的子类的CRTP缺少一个在基类中"没有真正"实现的方法:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这编译得很好,但在运行时会导致分段错误.我怎么能避免这种情况?我更喜欢这里的编译器错误(使用gcc 4.6.3).

Ker*_* SB 6

由于您的类实际上没有成员AMethod,因此您最终会调用CRTP基础的成员,从而为您提供无限递归.

简单的解决方案不是在整个地方重用名称,而是有一个被调用AMethod,另一个AMethodImpl 或类似的东西:

void AMethod()
{
    static_cast<T*>(this)->AMethodImpl();
}
Run Code Online (Sandbox Code Playgroud)