让我们考虑以下代码:
template<typename T>
struct Base{
};
struct Derived: Base<Derived>{
};
int main() {
Base<Derived>* base_ptr = new Derived();
}
它有效,我的意思是它编译。和课程版本相同:
template<typename T>
class Base{
};
class Derived: Base<Derived>{
};
int main() {
Base<Derived>* base_ptr = new Derived();
//ERROR ‘Base<Derived>’ is an inaccessible base of ‘Derived’
}
答案 0 :(得分:5)
因为对于结构体而言,基类的默认访问权限是public
,而对于类的private
,
使用
class Derived: public Base<Derived>{
^^^^^^
使它等同于第一个例子。
这与CRTP无关,没有CRTP会得到完全相同的错误:
class Base { };
class Derived : Base { };
Base* base_ptr = new Derived();