Accessing public inherited Template data members [duplicate]

ぐ巨炮叔叔 提交于 2020-03-21 17:38:13

问题


I require some clarification on the question why do we need the scope resolution operator or this pointer to access publicly inherited members from a template base class. As I understand it is for adding clarity but then how does this add any further clarity than just point that it is a member of the class.

To make my question clearer I have added some code.

#include <iostream>
using namespace std;

template <class T, class A>
class mypair {
        public:
         T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}

        virtual void printA() 
        {   
        cout<<"A"<<a<<endl;
        cout<<"B"<<b<<endl;
        }   
};







template <class T, class A>
class next: mypair<T,A>
{
public:

        next (T first, T second) : mypair<T,A>(first, second)
        {   
        }   

        void printA() 
        {   
        cout<<"A:"<<mypair<T,A>::a<<endl; // this->a; also works 
        cout<<"B:"<<mypair<T,A>::b<<endl; // this-b;  also works
        }   

};


int main () {
  next<double,float>  newobject(100.25, 75.77);
  newobject.printA();
  return 0;
}

Output:

A:100.25
B:75.77

If i remove the scope(or this operator) then the out of scope error comes. But why do we need a scope for publicly inherited members.

Some thoughts on this would be great.


回答1:


Refer to Name lookup - Using the GNU Compiler Collection (GCC)

By adding explicit prefix mypair<T, A>, or this->, you make printA template argument dependent. Then the definitions will be resolved during template instantiation stage.



来源:https://stackoverflow.com/questions/3615867/accessing-public-inherited-template-data-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!