[英]Accessing protected members of derived class with CRTP
我正在使用CRTP,並且在訪問派生類的受保護成員時遇到問題。
這是示例,靠近我的代碼:
template< typename Self>
class A {
public:
void foo( ) {
Self s;
s._method( s); //ERROR, because _method is protected
}
protected:
virtual void _method( const Self & b) = 0;
};
class B : public A< B> {
protected:
void _method( const B & b) {}
};
我了解,我必須使用friend關鍵字。 但是我不知道將它放在A <Self>類中的什么位置 。 我知道我可以在B中將void _method(const B&b)公開,但是我不想這樣做。 我也不可能在B中使用任何關鍵字!
我剛剛找到了解決方案。 感謝您的回答。 我只需要更改此行:
s._method( s); //ERROR, because _method is protected
至
( ( A< Self> &) s)._method( s);
而且有效! http://ideone.com/CjclqZ
template< typename Self>
class A {
public:
void foo( ) {
Self s;
s._method( s); //ERROR, because _method is protected
}
protected:
virtual void _method( const Self & b) = 0;
};
template< typename Self>
class B : public A< Self> {
protected:
void _method( const Self & b) {}
};
用這種方式做; 在A類中,_method是純虛擬的,因此您必須在B類中覆蓋它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.