小编Jon*_*gle的帖子

C++类模板函数可以访问嵌套类私有成员

以下代码无法按预期编译:

#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 ++对模板成员函数有不同的访问规则来访问嵌套类?

c++ templates private instantiation

3
推荐指数
1
解决办法
270
查看次数

标签 统计

c++ ×1

instantiation ×1

private ×1

templates ×1