Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 350
kirakun Avatar asked Feb 27 '11 05:02

kirakun


2 Answers

"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)
like image 153
James McNellis Avatar answered Nov 04 '22 17:11

James McNellis


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.

like image 34
Jeremiah Willcock Avatar answered Nov 04 '22 17:11

Jeremiah Willcock