gpt4 book ai didi

c++ - typedef 和在同一范围内使用相同名称的声明

转载 作者:可可西里 更新时间:2023-11-01 16:18:13 24 4
gpt4 key购买 nike

我搜索了 C++11 标准(嗯,n3242 草案)和互联网,但找不到准确的答案。下面的代码可以在 clang 3.2 和 g++ 4.7.2 以及 Visual Studio 2010 中正常编译,但我预计会出现错误。

#include <iostream>
#include <typeinfo>


typedef int a_t;


namespace a_ns
{
class a_t {};
}


using a_ns::a_t;


int main()
{
a_t a;
std::cout << typeid(a).name() << std::endl;
return 0;
}

内置:

clang -std=c++11 -pedantic -Wall -o a a.cpp -lstdc++
g++ -std=c++11 -pedantic -Wall -o a a.cpp -lstdc++
cl -EHsc -GR a.cpp

clang 和 g++ 生成的可执行文件打印“i”,这似乎表明 a 是 int 类型并且 typedef 占优势。 cl 生成的可执行文件打印“class a_ns::a_t”,这似乎表明 Visual Studio 更喜欢 using 声明。

我希望代码不会根据以下标准摘录进行编译。我希望出现类似于“使用声明的目标与范围内已存在的声明冲突”的错误。

7.1.3.6 Similarly, in a given scope, a class or enumeration shall not be declared with the same name as a typedef-name that is declared in that scope and refers to a type other than the class or enumeration itself.

7.3.3.1 A using-declaration introduces a name into the declarative region in which the using-declaration appears.

7.3.3.2 Every using-declaration is a declaration [...]

在解释这种行为的标准中,我可能缺少某些东西(或者我太累了,看不到明显的东西),但我似乎找不到它。

谢谢。

最佳答案

没错,您所显示的内容使代码无效。还有 3.3.1p4 也使它无效(参见 7.3.3p13)。

对于现实测试,我使用 ICC 进行了测试,它按预期拒绝了它。

关于c++ - typedef 和在同一范围内使用相同名称的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124077/

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