以下代码无法按预期编译:
#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
}
};
但是,如果我将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?
}
};
这是gcc中的错误吗?还是c ++对于模板成员函数访问嵌套类有不同的访问规则?
这是gcc中的错误吗?还是c ++对于模板成员函数访问嵌套类有不同的访问规则?
都不行
实现不得隐式实例化函数模板,变量模板,成员模板,非虚拟成员函数,成员类,类模板的静态数据成员或constexpr if语句的子语句([stmt。 if]),除非需要此类实例化。
就是说,Enclosing::EnclosingFun()
这里没有实例化。将调用添加到它会导致它被实例化,然后您将得到错误,例如
prog.cc:8:30: error: 'int Enclosing::Nested::y' is private within this context
std::cout << t << n->y; // OK? Why?
~~~^
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句