这段代码:
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; };
这是一个库/编译器的bug?
解决方法
C标准为各种智能指针指定允许模板参数为不完整类型.
此信息不是容器类型.因为它是未指定的,所以允许一个实现接受一个容器类模板的不完整类型而不是另一容器类模板,并且仍然是一致的.
为了使您的代码可移植,避免在类型完成之前制作任何类型的容器.
正式地,这个约束在以下适用于你的代码的规则(17.6.4.8)中找到:
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.