在我自己的命名空间中定义 size_t 会产生歧义或其他错误吗?
Can defining size_t in my own namespace create ambiguity or other bugs?
我有以下代码定义 size_t
相当于 std::size_t
和 ::size_t
如果我包含 <cstddef>
.
// h.hpp
namespace N {
using size_t = decltype(sizeof(int));
}
// a.hpp
#include <h.hpp>
namespace N {
class C {
size_t size() const;
};
void f(size_t);
}
// ^^^ These use N::size_t!
这是否以任何方式违反了 C++ 标准,这是否会导致使用这些 header 和任何其他标准 header 的任何代码中定义 std::size_t
和 ::size_t
? 如果有人不能在任何上下文中互换使用 std::size_t
和 N::size_t
或者只使用 size_t
在任何上下文中都会引起歧义。
// someOtherFile.cpp
#include <a.hpp>
#include <cstdint>
namespace N {
// Can there be any problem here? (Inside N::)
}
// Or here? (Outside N::)
我的猜测是不,因为我的和标准的 size_t
都只是 unsigned long (long) int
的类型别名
您的别名不会造成任何问题。它出现在它自己的命名空间范围内,所以别名声明不会重新声明任何东西。即使客户端代码会不负责任地做一些顽皮的事情,比如:
using namespace std;
using namespace N;
size_t foo;
这仍然很好,因为 size_t
是同一类型,无论别名来自哪个命名空间。仅当来自不同名称空间的相同名称引用 不同 个实体时,名称查找才会失败:
[namespace.udir]
6 If name lookup finds a declaration for a name in two different
namespaces, and the declarations do not declare the same entity and do
not declare functions, the use of the name is ill-formed.
根据 C++ 标准,"entity" 涵盖了广泛的内容,包括类型。这就是症结所在,因为类型别名不是类型,它只是现有类型的新名称。所以这两个(不合格的)别名命名相同的东西。
我有以下代码定义 size_t
相当于 std::size_t
和 ::size_t
如果我包含 <cstddef>
.
// h.hpp
namespace N {
using size_t = decltype(sizeof(int));
}
// a.hpp
#include <h.hpp>
namespace N {
class C {
size_t size() const;
};
void f(size_t);
}
// ^^^ These use N::size_t!
这是否以任何方式违反了 C++ 标准,这是否会导致使用这些 header 和任何其他标准 header 的任何代码中定义 std::size_t
和 ::size_t
? 如果有人不能在任何上下文中互换使用 std::size_t
和 N::size_t
或者只使用 size_t
在任何上下文中都会引起歧义。
// someOtherFile.cpp
#include <a.hpp>
#include <cstdint>
namespace N {
// Can there be any problem here? (Inside N::)
}
// Or here? (Outside N::)
我的猜测是不,因为我的和标准的 size_t
都只是 unsigned long (long) int
您的别名不会造成任何问题。它出现在它自己的命名空间范围内,所以别名声明不会重新声明任何东西。即使客户端代码会不负责任地做一些顽皮的事情,比如:
using namespace std;
using namespace N;
size_t foo;
这仍然很好,因为 size_t
是同一类型,无论别名来自哪个命名空间。仅当来自不同名称空间的相同名称引用 不同 个实体时,名称查找才会失败:
[namespace.udir]
6 If name lookup finds a declaration for a name in two different namespaces, and the declarations do not declare the same entity and do not declare functions, the use of the name is ill-formed.
根据 C++ 标准,"entity" 涵盖了广泛的内容,包括类型。这就是症结所在,因为类型别名不是类型,它只是现有类型的新名称。所以这两个(不合格的)别名命名相同的东西。