C++ 使用 std::p air 模板专用化定义树节点数据结构
C++ Defining Tree Node Data Structure with std::pair Template Specialization
请考虑以下 (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;
}
相关文章:
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- C++模板专用化 - 无法匹配函数定义
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 为什么模板专用化需要内联定义?
- 模板专用化会导致未定义的引用错误
- 对专用模板成员的未定义引用
- 在模板类内部定义的枚举上的嵌套类的部分专用化
- 没有针对完全专用模板类的外联虚拟方法定义
- 使用模板模板参数进行模板定义的函数专用化
- 如何从具有专用化的类模板定义静态成员变量?
- 如何为模板化类的模板化函数定义模板专用化
- C++模板专用化成员函数的定义
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 如何在另一个类模板中定义完全专用类的构造函数
- C++跨文件共享的模板专用化定义
- 如何专用/分配自定义内存位置,以便可以在C 中编辑该位置
- 元组的定义和初始化,其组件属于同一模板化类,但具有不同的专用化
- 在子类中定义可变参数函数专用化
- 为类模板的单个成员定义专用化
- UE4自定义专用服务器(碰撞,命中框)