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

时间:2010-03-18 07:26:14

标签: c++ vector local-class

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

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

2 个答案:

答案 0 :(得分: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). ]"

在c.l.c ++。moderated上提出了一个解决方法here

<强>更新: 有一些讨论为什么不能将local-classes作为模板参数? c.std.c ++上的链接herehere讨论相同的内容。

答案 1 :(得分:3)

简答: 因为C ++标准是这样说的(部分14.3.1

答案很长: 在C ++标准化的时候,C ++标准委员会认为会出现实现和性能问题。这些担忧被证明是没有根据的,截至C ++ 0x标准的最终草案,他们已经推翻了这一决定。


在更实际的说明中,一些编译器已经支持新的C ++ 0x规则:

  • 对于MacOSX,您需要使用-std=c++0x命令行参数gcc&gt; = 4.5
  • 对于Microsoft编译器,您需要&gt; = vc8 / VS2005 ,不需要 /Za选项(禁用语言扩展名)
相关问题