c++ - 什么是 C++ 中的未命名类型?

标签 c++ templates types standards

在阅读 C++ 标准 ANSI ISO IEC 14882 2003 时,我发现了以下内容:

14.3.1.2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

虽然我知道什么是局部类型和复合类型,但什么是未命名类型?如果一个类型是未命名的,你怎么能尝试在模板中使用它,这促使标准口头排除它?

最佳答案

“未命名类型”实际上是指“未命名的枚举或类类型”[有关更多信息,请参阅此答案的注释]。枚举或类类型不必有名称。例如:

struct { int i; } x; // x is of a type with no name

您可以尝试通过参数推导使用未命名类型作为模板参数:

template <typename T> void f(T) { }

struct { int i; } x;
f(x); // would call f<[unnamed-type]>() and is invalid in C++03

请注意,此限制已在 C++0x 中取消,因此此有效(您还可以使用本地类型作为类型模板参数)。在 C++0x 中,您还可以使用 decltype 来“命名”一个未命名的类型:

template <typename T> void g() { }

struct { int i; } x;
f<decltype(x)>(); // valid in C++0x (decltype doesn't exist in C++03)

关于c++ - 什么是 C++ 中的未命名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131691/

相关文章:

c++ - 可继承类的模板类的转换

c++ - 递归构造 unsigned int 的可变参数模板

haskell - 意外的重叠实例错误

sql - Hive - 通过跨组聚合值来创建映射列类型

c++ - 空函数作为指针

c++ - 打印所有给定N的偶数或奇数

c++ - 从另一个模板结构继承的模板结构

list - 为什么 Haskell 基础库中没有 "non-empty list"类型?

c++ - C++ 中的 if 语句行为真的很奇怪

c++ - 指针比较