我有一些课
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
成为朋友
答案 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;
}
};