为什么std :: vector不能采用本地类型?

ano*_*non 14 c++ vector local-class

void foo() {
  struct Foo { .. };
  std::vector<Foo> vec; // why is this illegal?
}
Run Code Online (Sandbox Code Playgroud)

我不会把Foo归还外面的世界.它只是我在函数中使用的临时类型.

Abh*_*hay 14

本地类不能是模板参数.因为标准说: -

14.3.1第2段:"本地类型,没有链接的类型,未命名的类型或从这些类型中复合的类型不得用作模板类型参数的模板参数."

[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). ]"
Run Code Online (Sandbox Code Playgroud)

这里建议使用clc ++.moderated 一个解决方法.

更新:有一些讨论为什么不能将local-classes作为模板参数?这些链接在这里这里的c.std.c ++讨论相同.