以下代码无法按预期编译:
#include<iostream>
class Enclosing {
int x;
class Nested { int y; };
void EnclosingFun(Nested *n) {
std::cout << n->y; // Compiler Error: y is private in Nested
}
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我将EnclosingFun更改为模板成员函数,编译器(gcc-7)不会抱怨访问y:
#include<iostream>
class Enclosing {
int x;
class Nested { int y; };
template <typename T>
void EnclosingFun(Nested *n, T t) {
std::cout << t << n->y; // OK? Why?
}
};
Run Code Online (Sandbox Code Playgroud)
这是gcc中的错误吗?或者c ++对模板成员函数有不同的访问规则来访问嵌套类?