【发布时间】:2018-03-11 03:32:51
【问题描述】:
以下代码无法按预期编译:
#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
}
};
但是,如果我将 EnclosureFun 更改为模板成员函数,编译器 (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?
}
};
这是 gcc 中的错误吗?还是c++对模板成员函数访问嵌套类有不同的访问规则?
【问题讨论】:
-
你从来没有调用过它,这个函数没有被实例化。在 main 中添加调用。
-
@S.M.您应该将其扩展为答案。
-
@RSahu 好的,我将评论扩展到答案。但它已经在我面前得到了回答。
标签: c++ templates private instantiation