gpt4 book ai didi

c++ - 当结构声明被变量隐藏时的名称解析

转载 作者:行者123 更新时间:2023-12-03 07:00:34 24 4
gpt4 key购买 nike

让我们考虑以下演示程序。

#include <iostream>

struct A
{
struct B
{
int b = 10;
};
int B = 20;
};

template <class T>
struct C
{
void f() const
{
typename /*struct*/ T::B b;
int x = b.b;
std::cout << "x == " << x << '\n';
}
};

int main()
{
C<A>().f();
}
正如所看到的成员声明 struct B在结构中 A被数据成员 B 的声明隐藏了具有类型 int .
所以在模板结构声明的函数定义中
typename /*struct*/ T::B b;
依赖名称 T::B不应该被发现。
然而编译器 gcc 8.3程序编译成功,程序输出
x == 10
另一方面,编译器 Visual C++ 2019 不会编译程序并发出语法错误。
那么是不是编译器的bug gcc 8.3 ?
第二个问题是,如果允许这种带有详细类型说明符的构造(带有未注释的关键字结构),那将是很自然的。
typename struct T::B b;
然而,两个编译器都认为构造不正确。
真的不正确吗?

最佳答案

它应该是编译器 gcc 8.3 的一个错误。因为typename T::B的标准规则应解析为变量而不是 struct B ,这些规则列在下面:

A class name or enumeration name can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.


上面的规则说 struct B的名字被声明名称隐藏 int B = 20;

When a qualified-id is intended to refer to a type that is not a member of the current instantiation ([temp.dep.type]) and its nested-name-specifier refers to a dependent type, it shall be prefixed by the keyword typename, forming a typename-specifier. If the qualified-id in a typename-specifier does not denote a type or a class template, the program is ill-formed.


The usual qualified name lookup is used to find the qualified-id even in the presence of typename.


上面的规则说关键字 typename不影响 qualified name lookup的结果, 换句话说,关键字 typename不要求名称查找过程只查找类型。
所以,在 A的范围内, int B = 20;的声明和 struct B 都找到了,然后变量隐藏 class name .所以,根据规则 如果 typename-specifier 中的qualified-id 不表示类型或类模板,则程序格式错误 ,程序应该是格式错误的。因此, 海湾合作委员会 8.3 是错的。
此外,不仅 GCC 8.3但更高的版本都是错误的。

关于c++ - 当结构声明被变量隐藏时的名称解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64335766/

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