C++ 使用 std::p air 模板专用化定义树节点数据结构



请考虑以下 (C++) 代码

class A {...};
namespace std
{
    template<>
    struct hash<A>
    {
        size_t operator() (const A& a) const
        {
            // returns unique hash based on components of A
        };
    };
}
class B
{
    std::unordered_map<A, B> *children; //ignore the fact that its a pointer for now
};

当我编译时,编译器告诉我 std::p air<_T1, _T2>::second 的类型不完整(以及其他错误),我认为这是我在 B 中声明它的错,但我不知道我应该如何正确做到这一点。

我认为标准库通常(必须)不支持不完整的类型。

我记得,Boost 容器库明确支持这一点:

不完整类型的容器

  • 递归容器
  • 键入擦除

标准容器呢?不完整类型的容器已经被讨论了很长时间,正如Matt Austern的伟大文章(标准图书馆员:不完整类型的容器)中所解释的那样:

"与我的大多数专栏不同,这个专栏是关于C++标准库无法做到的事情:将不完整的类型放在其中一个标准容器中。本专栏解释了为什么你可能想要这样做,为什么标准化委员会禁止它,即使他们知道它很有用,以及你可以做些什么来绕过限制。

Boost.Container 提供的所有容器都可用于定义递归容器。

在科里鲁现场观看

#include <boost/container/vector.hpp>
#include <boost/container/list.hpp>
#include <boost/container/map.hpp>
#include <boost/container/stable_vector.hpp>
#include <boost/container/string.hpp>
using namespace boost::container;
struct data
{
   int               i_; 
   vector<data>      v_; //A vector holding still undefined class 'data'
   list<data>        l_; //A list holding still undefined 'data'
   map<data, data>   m_; //A map holding still undefined 'data'
   friend bool operator <(const data &l, const data &r)
   { return l.i_ < r.i_; }
};
struct tree_node
{
   string name;
   string value;
   //children nodes of this node
   list<tree_node>        children_;
};
int main()
{
   //a container holding a recursive data type
   stable_vector<data> sv;
   sv.resize(100);
   //Let's build a tree based in
   //a recursive data type
   tree_node root;
   root.name  = "root";
   root.value = "root_value";
   root.children_.resize(7);
   return 0;
}

最新更新