Alex Rivera | Logout

Accessing private member variables from a templated class assignment operator

Asked 2011-08-05T14:42:15.723
20

I have a container class that is templatized. I am overloading the assignment operator such that derived types can also be assigned.

My problem is, when the type is not the same, I cannot access the private members of the container class. What is the best approach to gaining access? The member variables cannot be made accessible through public getters. Thanks!

Example Code:

// Note: var is private

template <class T>
Container<T>& Container<T>::operator=(const Container<T>& rhs) {
   if(*this != rhs) var = rhs.var; // works for same type
   return *this;
}

template <class T>
template <typename U>
Container<T>& Container<T>::operator=(const Container<U>& rhs) {
   if(*this != rhs) var = rhs.var; // does NOT work for different types
   return *this;
}
Edit
Report

1 Answer

22

Since you want to access private members of template class instantiated with different types, you've to make other templates as friend of the template class as:

template <class T>
class Container
{
      template<class U> 
      friend class Container;

};

Note that if T and U are different types, then Container<T> and Container<U> are two completely different classes; one cannot access private members of other if you don't make friend one of other.

Also note that in the above code all instantiations of the class template are friend of each other. That is, if you instantiate it with char, int, short, then

  • Container<int> will be friend of both Container<char> and Container<short>.
  • Container<char> will be friend of both Container<int> and Container<short>.
  • Container<short> will be friend of both Container<int> and Container<char>.

The interesting phrase here is : "friend of each other". Usually this doesn't happen. For example, if you have a class like this:

class A
{
   friend class B;
};

Then here only B is friend of A. A is NOT friend of B. They're NOT "friend of each other". B can access private members of A, but A cannot access private members of B. That is the difference between this class and the template class above.

answered 2011-08-05T14:48:20.017

Your Answer