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

时间:2013-09-19 23:20:46

标签: c++ c++11 stl

考虑以下(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 :: pair&lt; _T1,_T2&gt; :: second有不完整的类型(以及其他错误),我认为这是我在B中声明它的错,但是我没有知道我该怎么做才能正确。

1 个答案:

答案 0 :(得分:4)

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

我记得,Boost Container库明确支持这一点,但是:

  

Containers of Incomplete Types

           

标准容器怎么样?正如Matt Austern的伟大文章(The Standard Librarian: Containers of Incomplete Types)所解释的那样,不完整类型的容器已经讨论了很长时间:

     
    

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

  

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

查看 Live on Coliru

#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;
}