在阅读 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/