朋友&&模板

时间:2016-04-28 19:22:18

标签: c++ templates friend

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

#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。 任何人都知道如何实现这一目标?

由于

2 个答案:

答案 0 :(得分:3)

友谊不会像你想要的那样运作。当你有

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>可以访问私有成员(Live Example)。

答案 1 :(得分:1)

你需要反过来做。 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;
}

Live Demo

相关问题