如何有一个unordered_map值类型是它的类? [英] How to have an unordered_map where the value type is the class it's in?

查看:423
本文介绍了如何有一个unordered_map值类型是它的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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'

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

However, this code compiles just fine:

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

这是一个库/编译器错误吗?

Is this a library/compiler bug?

推荐答案

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

The C++ standard specifies for the various smart pointers that the template parameter is allowed to be an incomplete type.

没有给出容器类型。因为它是未指定的,一个实现允许一个容器类模板接受一个不完整的类型,而不是另一个,并仍然符合。

This information is not given for container types. Because it is unspecified, an implementation is allowed to accept an incomplete type for one container class template and not another, and still be conformant.

为了使代码可移植,避免

To make your code portable, avoid making containers of any type before the type is completed.

形式上,此约束在以下规则(17.6.4.8)中找到,它适用于您的代码:

Formally, this constraint is found in the following rule (17.6.4.8) which applies to your code:


在某些情况下(替换函数,处理函数,用于实例化标准库模板组件的类型操作),C ++标准库取决于一个C ++程序。如果这些组件不满足其要求,则该标准对实施没有要求。

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:

...


  • 如果在实例化模板组件时将不完全类型用作模板参数,除非该组件特别允许。

这篇关于如何有一个unordered_map值类型是它的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆