C++,前向声明和递归数据类型

标签 c++ templates stl

我希望能够有一个 map ,其中的值是指向 map 的指针。有点像

std::map<KeyType, const_pointer_to_this_map's_value_type>

我知道我可以使用 const void * 而不是 const_pointer_to_this_map's_value_type。

我见过循环数据类型定义的技巧,例如 https://gist.github.com/tivtag/1208331http://qscribble.blogspot.fr/2008/06/circular-template-references-in-c.html但我不确定它们是否以及如何应用于我的案例。

他们在那里使用自己的类(顶点和边;A 和 B),但这里 std::map 和 std::map::value_type 已经在 STL header 中定义,我不能只用组合类。

有没有办法定义上面的 map ?

最佳答案

只需将其包装在一个结构中即可。您需要为该类型命名以便能够引用它。

template<class T>
class Graph {
    std::map<T, const Graph<T>*> data;
public:
    // ...
};

在 C++11 中,您还可以使用带有前向声明的 typedef 模板别名来实现:

namespace {

template<class T>
struct GraphWrap {
    class type;
    typedef std::map<T, const typename GraphWrap<T>::type*> type;
};

}

template<class T>
using Graph = typename GraphWrap<T>::type;

当然,在这里使用 std::map 可能有点误导,因为您使用键类型参数作为容器的值类型。就像 Mooing Duck 所说的那样,您似乎正在对一个有向图建模,其中每个节点最多有一个传出边。如果你想用图表做点什么,那里有图表库——如果你在做其他事情,或者如果你只是想学习,那就是另一回事了。

关于C++,前向声明和递归数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305158/

相关文章:

c++ - std::array to pointer 访问冲突错误

c++ - 将 pthread_mutex_t 和 pthread_cond_t 作为类成员静态变量有什么优势吗?

C++反向整数序列实现

c++ - 如何在自己的类中使用默认比较器?

c++ - 类和结构的高效 push_back

c++ - 如何避免在嵌套循环中重复自己

c++ - 确认对 typedef 和 #define 的理解

c++ - 如何对嵌套类型进行部分模板特化?

python - 如何检查 django 模板中的 TEMPLATE_DEBUG 标志?

c++ - 如何实现能够接受 IO 操纵器的 StringBuilder 类