模板化已模板化的 Base class 的 Derived class
Templating a Derived class of a Base class that is already templated
我收到编译器错误“使用未声明的标识符‘_storage’”
#include <iostream>
struct Storage{
int t;
};
struct DerivedStorage : Storage{
int s;
};
struct DerivedStorage2 : DerivedStorage{
int r;
};
template<typename DS = Storage>
class Base{
public:
DS* _storage = nullptr;
Base(){
_storage = new DS();
}
void m(){
_storage->t++;
}
};
template<typename DS = DerivedStorage>
class Derived : public Base<DS>{
public:
void m2(){
_storage->s++; //error here
}
};
template<typename DS = DerivedStorage2>
class Derived2 : public Derived<DS>{
public:
void m3(){
_storage->r++; //error here
}
};
int main(int argc, const char * argv[]) {
Derived2<DerivedStorage2> t;
for(int i = 0;i<3;i++){
t.m3();
}
return 0;
}
知道问题出在哪里吗?
因为Derived
本身没有名为_storage
的成员变量,所以使用this->_storage
来访问Base
的_storage
。
void m2(){
this->_storage->s++;
}
我收到编译器错误“使用未声明的标识符‘_storage’”
#include <iostream>
struct Storage{
int t;
};
struct DerivedStorage : Storage{
int s;
};
struct DerivedStorage2 : DerivedStorage{
int r;
};
template<typename DS = Storage>
class Base{
public:
DS* _storage = nullptr;
Base(){
_storage = new DS();
}
void m(){
_storage->t++;
}
};
template<typename DS = DerivedStorage>
class Derived : public Base<DS>{
public:
void m2(){
_storage->s++; //error here
}
};
template<typename DS = DerivedStorage2>
class Derived2 : public Derived<DS>{
public:
void m3(){
_storage->r++; //error here
}
};
int main(int argc, const char * argv[]) {
Derived2<DerivedStorage2> t;
for(int i = 0;i<3;i++){
t.m3();
}
return 0;
}
知道问题出在哪里吗?
因为Derived
本身没有名为_storage
的成员变量,所以使用this->_storage
来访问Base
的_storage
。
void m2(){
this->_storage->s++;
}