c++ - inheritance doesn't work as it should when using templates -
this question has answer here:
- template inheritance c++ 3 answers
i having issue inheritance. created example show more or less issue. thing if publicly derive class publicly derives class must have access protected members in original class way. doesn't seem case when i'm using templates.
in fact, example below complains on line 'n++;' saying 'n' not declared in scope. however, if without templates. code compiles fine. going on?
#include<iostream> template<typename t> class base{ protected: t n; public: t getn(); base(); }; template<typename t> t base<t>::getn(){ return n; } template<typename t> base<t>::base(){ n = 8; } template<typename t> class daddy: public base<t>{ protected: public: }; template<typename t> class granny: public daddy<t>{ protected: public: t plusone(); }; template<typename t> t granny<t>::plusone(){ //this->n = this->n + 1; n++; return n; } int main(){ granny<int> oldmommy; int su = oldmommy.getn(); std::cout << su << std::endl; su = oldmommy.plusone(); std::cout << "plusone" << su << std::endl; return 0; }
btw. tell me if should post code no templates compare..
a quick fix apply this
before variable:
this->n = this->n + 1; return this->n;
the reason compiler makes no assumptions template base class members (n
in case, dependent on type t) in case there partial specialization of base class not include of these members.
Comments
Post a Comment