[英]Access to protected members of base class with CRTP
I would like to ask you a question about the CRTP. 我想问你一个关于CRTP的问题。 Suppose you have a base class and a derived class as below.
假设您有一个基类和派生类,如下所示。 Is there a way to extract the member "value" from the base class in one of the member functions of the derived class (eg, "foo")?
有没有办法从派生类的一个成员函数(例如“foo”)中的基类中提取成员“value”?
The compiler tells me: error: 'value' was not declared in this scope 编译器告诉我:错误:在此范围内未声明'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;
}
Because you are directly inheriting from a base class that depends on T
you need to use this->
to access your data members: 因为您直接从依赖于
T
的基类继承,所以您需要使用this->
来访问您的数据成员:
std::cout << "Its own value is : " << this->value << std::endl;
// ^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.