朋友&&模板

Friend && Template

本文关键字:模板 朋友      更新时间:2023-10-16

我实际上是想让一个模板类与另一个模板类成为朋友。像这样:

#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;
}

但我做不到,gcc 说int Test1<T>::wantToBeFriend is private.有人知道如何实现这一目标吗?

谢谢

友谊不会像你试图让它工作的方式那样工作。 当你有

friend class Test1<T>;

这意味着Test1<T>可以访问Test2<T>的私人成员。 它不允许Test2<T>访问Test1<T>的私人成员。 如果是这样,那么拥有私人成员就没有意义了,因为您可以让自己成为该类的朋友并访问它们。

如果我们像这样切换它

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

然后代码编译得很好,就像现在一样Test2<T>可以访问私有成员(实时示例)。

你需要反过来做。 Test1需要将Test2声明为友元类:

#include  <iostream>
template <typename T> class Test2;
template < typename T >
class  Test1 {
  template <typename U> friend class Test2; 
  private:
    static int  wantToBeFriend;
};
template < typename T >
int  Test1<T>::wantToBeFriend = 1;

template < typename T >
class  Test2 {
  public:
    void  run() {
      std::cout << Test1<T>::wantToBeFriend << std::endl;
    }
};
int main()
{
//  Test1<int> test1;
  Test2<int> test2;
  test2.run();
  return 0;
}

现场演示