One case to use of the `this` pointer explicitly in template class inherit

template
class A
{
  protected:
     int _m;
  public:
     int getM() { return _m; }
     void setM(int m) { _m = m; }
};

template <class T>
class B: public A<T>
{
  public:
     int getMM() { return this->_m; };
     //int getMM2() { return _m; }; //error when use template, if no template, no problem at all.

};


If you omit this->, the compiler does not know how to treat _m, since it may or may not exist in all instantiations of A. In order to tell it that _m is indeed a member of A<T>, for any T, the this->prefix is required. (even though any A<T> has the member, compiler didn't know)

OR

using A<T>::_m; // explicitly refer to a variable in the derived class


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章