gpt4 book ai didi

c++ - typedef 的名称查找在 GNU 编译器中有问题吗?

转载 作者:可可西里 更新时间:2023-11-01 18:28:03 25 4
gpt4 key购买 nike

下面的代码

#include <iostream>

typedef double A; // a global typedef

template <class Z> struct B // a template class...
{
A i{22.2}; // global typedef is in scope
typedef int A; // now a local typedef with the same name is introduced
A b{24}; // now the local typedef is in scope
Z c{36}; // a simple member of the template type
};

template <class Z> struct C : B<Z> // a template struct inheriting B
{
A a; // global typedef is in scope because we are in a template struct
C( ) : a(2.2){ }
};

int main( )
{
C<int> c;
std::cout << "c's members: "
<< c.a << ' '
<< c.i << ' '
<< c.b << ' '
<< c.c << std::endl;
std::cout << "their sizeof: "
<< sizeof(c.a) << ' '
<< sizeof(c.i) << ' '
<< sizeof(c.b) << ' '
<< sizeof(c.c) << std::endl;
}

不是由 GNU-g++ 4.9.2 编译的,而是由 clang 3.5.0 编译的,其行为正如我在嵌入式评论中试图解释的那样从产生的输出中可以看出。这是 GNU 编译器中的错误吗?诊断表明 typedef int A; 行在结构 B

error: changes meaning of ‘A’ from ‘typedef double A’

请注意,当层次结构不是由 template 构成时(当然还有 Z c{36}; 声明被移除)由 clang 执行的查找C 的范围内(我认为是正确的)在 B 的范围内找到 typedef 并考虑成员 a 是的输入整数;然后它发出关于初始化 double 常量 2.2...

变窄的警告

最佳答案

来自c++标准草案(N4140)

§3.3.7 [basic.scope.class]

2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

A i{22.2} 最初指的是全局 ::A。但是在 B::A 声明之后,当在 B 的完成范围内重新计算时,它将引用 B::A。这违反了上述规则。

要修复它,请使用完全限定名称:::A i{22.2}::A 始终引用全局 A,即使在声明了 B::A 之后也是如此,因此它不违反规则。

这不是 g++ 中的错误;这只是一个格式错误的程序。编译器不需要对违反规则的情况进行诊断,但也不需要接受它。

关于c++ - typedef 的名称查找在 GNU 编译器中有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569992/

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