如何将成员模板类声明为封闭类的朋友?

时间:2016-07-27 22:16:07

标签: c++ class oop c++11 nested

我有一些课

package.json

如何template<typename Fun, typename Arg> class TestBuilder { template<typename Int> class Helper {}; }; Helper成为friend的{​​{1}}? 我试过了:

TestBuilder

但这只是使template<typename Int> friend class Helper;

的朋友的名称空间范围Helper成为朋友

1 个答案:

答案 0 :(得分:3)

但是Helper是TestBuilder的嵌套类,不是吗? :)

因此,它可以访问外部类的成员(是,及其私有成员),请查看示例:

#include <iostream>

using namespace std;

template<typename Fun, typename Arg>
class TestBuilder
{
  int n;
  char c;

public:
  template<typename Int>
  class Helper
  {
  public:
    void print(TestBuilder& tb) {
      std::cout << tb.n << " " << tb.c << std::endl;
    }
  };
  TestBuilder(int n, char c) : n(n), c(c) {}

};

int main() {
        TestBuilder<int, int> tb(5, 'p');
        TestBuilder<int, int>::Helper<int> h;
        h.print(tb);

        return 0;
}

将输出:

C02QT2UBFVH6-lm:~ gsamaras$ pico main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp 
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
5 p

但是,如果你添加另一个类(不是嵌套的类,只是另一个类),它将无法访问TestBuilder的私有成员(当然!),请亲自看看:

class alienClass
{
public:
  /*
   That won't work, you will get:
   error: 'n' is a private member of 'TestBuilder<int, int>'
   error: 'c' is a private member of 'TestBuilder<int, int>'
  */
  void print(TestBuilder<int, int>& tb) {
    std::cout << tb.n << " " << tb.c << std::endl;
  }
};