这段代码:
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::list
和 std::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_list
、list
和 vector
的三个专门允许不完整模板参数的语句可在 [forwardlist.overview] 节中找到, [list.overview] , 和 [vector.overview] .
关于c++ - 如何拥有一个 unordered_map,其中值类型是它所在的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089388/