【问题标题】:Why can't a std::vector take a local type?为什么 std::vector 不能采用本地类型?
【发布时间】:2010-03-18 07:26:13
【问题描述】:
void foo() {
  struct Foo { .. };
  std::vector<Foo> vec; // why is this illegal?
}

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

【问题讨论】:

  • +1 好问题!没听说过=)
  • @anon:请问你用的是什么编译器?
  • @anon:虽然我可以在 Visual C++ 2005 中编译它,但我想如果那里真的提到这不符合标准。

标签: c++ vector local-class


【解决方案1】:

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

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 一种解决方法。

更新: 关于为什么不能将本地类作为模板参数进行了一些讨论? c.std.c++ 上的链接herehere 讨论了相同的内容。

【讨论】:

    【解决方案2】:

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

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


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

    • 对于 MacOSX,您需要 gcc >=4.5 和 -std=c++0x 命令行参数
    • 对于 Microsoft 编译器,您需要 >=vc8/VS2005没有/Za 选项(禁用语言扩展)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2018-11-08
      • 2023-04-05
      相关资源
      最近更新 更多