gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:01:56 26 4
gpt4 key购买 nike

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

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

最佳答案

Is this a bug in gcc? Or does c++ have different access rules for template member function to access nested classes?

也没有。

根据标准,§17.8.1 Implicit instantiation [temp.inst] ,

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class, a static data member of a class template, or a substatement of a constexpr if statement ([stmt.if]), unless such instantiation is required.

这意味着,Enclosing::EnclosingFun() 未在此处实例化。将调用添加到它会导致它被实例化,然后你会得到错误,例如

prog.cc:8:30: error: 'int Enclosing::Nested::y' is private within this context
std::cout << t << n->y; // OK? Why?
~~~^

LIVE

关于C++类模板函数可以访问嵌套类私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com