c++ - 问题重构奇怪地重复出现的模板模式

标签 c++ templates crtp

以下代码无法在 g++ 4.6.1 上编译:

template<class Base>
struct GetBase {
  Base * getBase() {
    return static_cast<Base *>(this);
  }
};

template<class Derived>
struct Parent : private GetBase<Derived> {
  using GetBase<Derived>::getBase;
  int y() {
    return getBase()->x();
  }
};

struct Child : public Parent<Child> {
  int x() {
    return 5;
  }
  int z() {
    return y();
  }
};

错误

In member function ‘Base* GetBase<Base>::getBase() [with Base = Child]’:
    instantiated from ‘int Parent<Derived>::y() [with Derived = Child]’
    instantiated from here
error: ‘GetBase<Child>’ is an inaccessible base of ‘Child’

将 static_cast 更改为 reinterpret_cast 将使代码编译并且在这种情况下它会起作用,但我想知道这是否在所有情况下都是可接受的解决方案?即,指向基类的指针是否与此不同?我假设如果 parent 有数据成员,多重继承可能会发生这种情况?如果 GetBase 是第一个父类(super class),那么 this 指针是否保证相等?

最佳答案

我想知道这是否在所有情况下都是可接受的解决方案?

否。(见下文)

指向基类的指针是否与此不同?

是的。

  • 对于多重继承,不能期望基类具有相同的地址。

  • 根据编译器的不同,带有 vtable 指针的派生类可能与没有 vtable 指针的基类具有相同的 this

当显式向上转换为基类时,static_cast 是合适的 C++ 转换。

关于c++ - 问题重构奇怪地重复出现的模板模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978260/

相关文章:

c++ - 尝试使用继承和模板来实现CRTP。 Visual Studio生成编译器错误

c++ - SVM + HOG,发现对象总是NULL

c++ - 需要明确类模板中友元运算符+的自动返回类型推导

c++ - 从模板函数内部的类型中删除 const-ness

c++ - 实现 CRTP 并发出 "undefined reference"

c++ - CRTP 模式不会触发完整模板实例化

c++ - typedef 的有效使用?

c++ - CascadeClassifier 检测的错误参数

c++ - 类和函数中的设计问题

c++ - 在 C++ 中抽象两个略有不同的函数的最佳方法是什么?