Search code examples
c++templatesfriend

Friend && Template


I'm actually trying to get one template class to be friend with another template class. Something like that:

#include  <iostream>

template < typename T >
class  Test1 {

  private:
    static int  wantToBeFriend;
};

template < typename T >
int  Test1<T>::wantToBeFriend = 1;


template < typename T >
class  Test2 {

  friend class Test1<T>;

  public:
    void  run() {

      std::cout << Test1<T>::wantToBeFriend << std::endl;
    }
};

int main()
{
  Test1<int> test1;
  Test2<int> test2;

  test2.run();
  return 0;
}

But I'm not able to do it, gcc say that int Test1<T>::wantToBeFriend is private. Anyone know how achieve that?

Thanks


Solution

  • Friendship does not work the way you are trying to make it work. When you have

    friend class Test1<T>;
    

    That means that a Test1<T> can access the private members of Test2<T>. It does not allow Test2<T> to access Test1<T>'s private members. If it did there would be no point in having private members as you could just make yourself a friend of the class and access them.

    If we switch it around like

    template < typename T >
    class  Test2;
    
    template < typename T >
    class  Test1 {
      friend class Test2<T>;
    
      private:
        static int  wantToBeFriend;
    };
    

    Then the code compile fine as now Test2<T> can access the private members(Live Example).