What is an unnamed type in C++?

情到浓时终转凉″ 提交于 2019-12-19 05:25:11

问题


As part of my toilet reading on the C++ Standard ANSI ISO IEC 14882 2003, I came across the following:

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.

While I get what a local type and a compound type are, what is an unnamed type? If a type is unnamed, how could you even attempt to use it in a template anyway, which prompted the standard to verbally exclude it?


回答1:


"Unnamed type" really means "unnamed enumeration or class type" [for more information, see the comments to this answer]. An enumeration or class type doesn't have to have a name. For example:

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

You could try to use an unnamed type as a template argument through argument deduction:

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

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

Note that this restriction has been lifted in C++0x, so this will be valid (you'll also be able to use local types as type template parameters). In C++0x, you could also use decltype to "name" an unnamed type:

template <typename T> void g() { }

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



回答2:


Think about the following code:

template <typename T>
void foo(const T&) {}

struct {
  int x;
} y;
foo(y);

That includes an unnamed type. Note that the rule is different in C++0x.



来源:https://stackoverflow.com/questions/5131691/what-is-an-unnamed-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!