[英]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
) 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
原因。
解決此問題的一種方法是使typedef A<Derived> base;
在B
公開或受保護,然后在fromB
可以添加friend base::base;
這將給A
訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.