c++ - 如何拥有一个 unordered_map,其中值类型是它所在的类?

标签 c++

这段代码:

class Foo {
    std::unordered_map<std::string, Foo> x;
};

给我一​​个错误:

/usr/include/c++/4.7/bits/stl_pair.h:94:11:
  error: 'std::pair<_T1, _T2>::second' has incomplete type
foo.cpp:4:7: error: forward declaration of 'class Foo'

然而,这段代码编译得很好:

class Foo {
    std::vector<Foo> x;
};

这是库/编译器错误吗?

最佳答案

C++标准对各种智能指针规定模板参数允许为不完整类型。

2017 及以后版本的标准允许容器的 value_type 在仅为容器模板 std::forward_list 实例化类模板时为不完整类型,std::liststd::vector,并且仅当分配器类型满足“allocator completeness requirements”时。默认分配器模板 std::allocator 始终满足分配器完整性要求。实例化容器类模板的任何成员仍然需要完整的 value_type

对于任何其他标准容器类型,不提供此信息。在未指定的情况下,允许实现接受一个容器类模板而不是另一个容器类模板的不完整类型,并且仍然保持一致。

为了使您的代码可移植,请避免在类型完成之前创建任何类型的容器,标准特别允许的情况除外。

形式上,一般约束在适用于您的代码的以下规则 ([res.on.functions]) 中找到:

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.

In particular, the effects are undefined in the following cases:

...

  • if an incomplete type is used as a template argument when instantiating a template component, unless specifically allowed for that component.

forward_listlistvector 的三个专门允许不完整模板参数的语句可在 [forwardlist.overview] 节中找到, [list.overview] , 和 [vector.overview] .

关于c++ - 如何拥有一个 unordered_map,其中值类型是它所在的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089388/

相关文章:

c++ - 穿 Frog 游戏的最佳图形选择?

c++ - 如何使用命名空间和类?

c++ - C++11 中有新的函数类型表达式格式吗?

c++ - 高效/可移植的有符号整数模正整数返回非负数?

c++ - 将 Sublime Text 与 cmake(构建系统)结合使用

c++ - 用于检查两个 double 值是否足够不同的 simd 代码

c++ - 字素簇中的最大代码点数

c++ - MDI Qt 应用程序中的链接器错误 : undefined reference to qInitResources_mdi()

c++ - ComboBox 子类列表框

c++ - 如何防止在加载程序中重新创建页面?