views:

228

answers:

2
void foo() {
  struct Foo { .. };
  std::vector<Foo> vec; // why is this illegal?
}

I'm not returning Foo to the outside world. It's just a temporary type that I use within the function.

+13  A: 

A local class can't be a template argument. Because the standard says:-

14.3.1 paragraph 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."

[Example:
template <class T> class X { /* ... */ };
void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as templateargument
X<S*> x4; // error: pointer to local type used as templateargument
}
-end example] [Note: a template type argument may be an incomplete
type (3.9). ]"

One workaround is suggested here on c.l.c++.moderated.

UPDATE: There was some discussion on why is it not possible to have local-classes as template arguments? The links here and here on c.std.c++ discuss the same.

Abhay
+2  A: 

Short answer: Because the C++ standard says so (section 14.3.1)

Long answer: At the time that C++ was standardized, the C++ standards committee believed that there would be implementation and performance issues. Those fears turned out to be unfounded and, as of the final draft of the C++0x standard, they've reversed the decision.


On a more practical note, some compilers already support the new C++0x rules:

  • For MacOSX you'll need gcc >=4.5 with the -std=c++0x command-line parameter
  • For the Microsoft compiler you'll need >=vc8/VS2005 without the /Za option (disable language extensions)
Joe Gauterin