为什么不编译以下 CRTP 层次结构?
Why doesn't the following CRTP hierarchy compile?
我正在尝试实现类的CRTP层次结构。我对基类感兴趣,可以访问链下派生类的数据成员:
#include <iostream>
template <class Derived>
class A {
public:
void showv() {
std::cout << static_cast<const Derived*>(this)->v << std::endl;
}
};
template <class Derived>
class B : public A< Derived > {
typedef A<Derived> base;
friend base;
};
class fromA : public A<fromA> {
typedef A<fromA> base;
friend base;
protected:
int v = 1;
};
class fromB : public B<fromB>
{
typedef B<fromB> base;
friend base;
protected:
int v = 2;
};
int main()
{
// This runs ok
fromA derived_from_a;
derived_from_a.showv();
// Why doesn't the following compile and complains about the protected member?
fromB derived_from_b;
derived_from_b.showv();
return 0;
}
演示
虽然第一个派生类(fromA
)按预期编译和运行,但第二个派生类(fromB
)派生自A
类,却没有。
- 朋友声明没有通过的原因是什么?
- 关于解决方法的任何建议?
问题是:我朋友的朋友不是我的朋友。
fromA
你有
typedef A<fromA> base;
friend base;
这使得A<fromA>
成为朋友,show
可以访问fromA
的受保护成员。
在fromB
你也有
typedef B<fromB> base;
friend base;
但这并不能使A
成为朋友,而是使B
成为你的朋友。 即使A是B
的朋友,这并不意味着它现在也是fromB
的朋友,这就是为什么您无法在show
中访问v
的原因。
解决此问题的一种方法是在B
中公开或保护typedef A<Derived> base;
然后在fromB
中添加friend base::base;
,从而授予A
访问权限。
相关文章:
- 如何重构类层次结构以避免菱形问题
- C++ 中模板化类型的类层次结构
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 继承层次结构并将元素添加到向量
- C++ 类层次结构中的"对齐"是什么意思?
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 类层次结构中的运算符重载
- 如何在层次结构中实现运算符使用?
- 反向层次结构中的可变参数模板参数
- 如何在继承层次结构中调用具有默认参数的构造函数?
- C++ 提升 - 包含类层次结构对象的类的序列化
- 在C++继承层次结构时提取实现者
- 在C++中将类实例添加到对象层次结构中的问题
- 确定大层次结构中基本指针的实际类型,无需dynamic_cast
- 在继承层次结构中复制和移动
- 模板冲突的类型-但类型应该是相同的cfr类层次结构
- 删除父/子窗口层次结构的最佳方法
- 为什么不编译以下 CRTP 层次结构?
- 如何在类层次结构中处理 CRTP
- CRTP层次结构类的非模板基类