rxu rxu - 2 months ago 21
C++ Question

Accessing Protected Attribute of Template Class

The following code doesn't work because the

t
member function can't access the attribute of its argument object.

How to declare template method t of template class A as a friend function of A?

For the code without template, there is no need to declare friend.

Code:

template <typename T>
class A{
protected:
T a;
public:
A(int i){
a = i;
}
template <typename T1>
void t(const A<T1> & Bb){
a = Bb.a;
}
};
int main(void){
A<int> Aa(5);
A<float> Bb(0);
Aa.t(Bb);
}


Compiler Error (icc test.cpp):

test.cpp(11): error #308: member "A<T>::a [with T=float]" (declared at line 4) is inaccessible
a = Bb.a;
^
detected during instantiation of "void A<T>::t(const A<T1> &) [with T=int, T1=float]" at line 17


Code without template:

class A{
protected:
int a;
public:
A(int i){
a = i;
}
void t(const A & Bb){
a = Bb.a;
}
};
int main(void){
A Aa(5);
A Bb(0);
Aa.t(Bb);
}

Answer

You can make all template instantiations friends of one another.

template <typename T>
class A {
   protected:

      // This makes A<int> friend of A<float> and A<float> friend of
      // A<int>
      template <typename T1> friend class A;

      T a;
   public:
      A(int i){
         a = i;
      }
      template <typename T1>
         void t(const A<T1> & Bb){
            a = Bb.a;
         }
};
int main(void){
   A<int> Aa(5);
   A<float> Bb(0);
   Aa.t(Bb);
}
Comments