簡體   English   中英

為什么以下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 )可以按預期進行編譯和運行,但是第二個派生類( fromBfromB是從A派生的類派生的。

  1. 沒有通過朋友聲明的原因是什么?
  2. 有任何解決方法的建議嗎?

問題是:我朋友的朋友不是我的朋友。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM