Search code examples
c++vectorlocal-class

Why can't a std::vector take a local type?


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.


Solution

  • 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.