与类和命名空间一起使用 差异/歧义

using with class & namespace differencies/ambiguity

本文关键字:差异 歧义 一起 命名空间      更新时间:2023-10-16

我只是好奇为什么用using指令来设计它。对于1)结构被视为命名空间,而对于2)它不是:

struct foo
{
  using type0 = int;
};
namespace bar
{
  using type1 = int;
}
using bar::type1; 
using type0 = foo::type0; // 1)
using foo::type0;         // 2)

clang version 3.3 (branches/release_33 186829)
clang -std=c++11 test.cpp
test.cpp:13:12: error: using declaration can not refer to class member
using foo::type0;

~~~~~^

gcc version 4.8.1
c++ -std=c++11 test.cpp
test.cpp:13:12: error: ‘foo’ is not a namespace
using foo::type0;

类不是名称空间;它们有严格的范围。类成员的名称(在类外访问时)必须始终以类名为前缀

using不允许更改。

#1之所以有效,是因为您为类中声明的类型创建了类型别名using name = typename;就是这么做的。在这种情况下,它与typedef没有什么不同。

#2不创建别名;该语法期望在名称空间内被赋予一个名称,以将其引入当前名称空间。