c++ - 为什么 crtp 适用于结构而不适用于类?

标签 c++ crtp

让我们考虑以下代码:

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’
}

最佳答案

因为对于结构,基类的默认访问权限是public,而对于类,它是private

使用

class Derived: public Base<Derived>{
               ^^^^^^

使其等同于第一个示例。

这与 CRTP 无关,如果没有 CRTP,您会得到完全相同的错误:

class Base { };
class Derived : Base { };
Base* base_ptr = new Derived();

关于c++ - 为什么 crtp 适用于结构而不适用于类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061228/

相关文章:

c++ - 导致过载解析头痛的原因是什么?

c++ - 混合 typedef 和 CRTP?

c++ - 迭代不同的 CRTP 派生类方法

c++ - 在奇怪的重复模板类中使用方法的返回类型作为另一个方法的参数类型

c++ - 如何在数组中显示二叉搜索树结果?

c++ - 升压::变体 - "no matching function for call"

c++ - vs 2010 : sqlstatementhandle and connection error 中的 mysql 和 c++

c++ - 为什么 boost::asio::ip::tcp::iostream 解析输入?

c++ - 通过重复的操作序列简化 GTest 用例

c++ - 类型删除 : Retrieving value - type check at compile time