加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使用一个unordered_map,其中值类型是它所在的类?

发布时间:2020-12-16 03:11:53 所属栏目:百科 来源:网络整理
导读:这段代码: class Foo { std::unordered_mapstd::string,Foo x;}; 给我一个错误: /usr/include/c++/4.7/bits/stl_pair.h:94:11: error: 'std::pair_T1,_T2::second' has incomplete typefoo.cpp:4:7: error: forward declaration of 'class Foo' 但是,这段
这段代码:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读