Home > front end >  Templating a Derived class of a Base class that is already templated
Templating a Derived class of a Base class that is already templated

Time:03-05

I get the compiler error "Use of undeclared identifier '_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;
}

Any idea what the problem is ?

CodePudding user response:

Because Derived itself does not have a member variable named _storage, use this->_storage to access Base's _storage instead.

void m2(){
  this->_storage->s  ;
}

Demo

  • Related