[英]Access to protected members of base class with CRTP
我想問你一個關於CRTP的問題。 假設您有一個基類和派生類,如下所示。 有沒有辦法從派生類的一個成員函數(例如“foo”)中的基類中提取成員“value”?
編譯器告訴我:錯誤:在此范圍內未聲明'value'
#include <iostream>
template <class T, class Implementation>
class FooBase
{
protected:
void fooBase(void) {};
int value;
};
template <class T>
class Foo : public FooBase <T, Foo<T>>
{
friend FooBase <T, Foo<T>>;
public:
void foo()
{
std::cout << "Its own value is : " << value << std::endl;
}
};
int main ()
{
Foo <int> foo;
foo.foo();
return 0;
}
因為您直接從依賴於T
的基類繼承,所以您需要使用this->
來訪問您的數據成員:
std::cout << "Its own value is : " << this->value << std::endl;
// ^^^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.