开发者

What is an unnamed type in C++?

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, 开发者_如何学Pythona 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?


"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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜