Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing public inherited Template data members [duplicate]

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.

like image 544
Sii Avatar asked Sep 01 '10 07:09

Sii


1 Answers

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.

like image 200
Ian Yang Avatar answered Oct 26 '22 05:10

Ian Yang