c++ - 圆形模板引用结构

标签 c++ templates structure cyclic-reference

我有一个关于循环模板引用的问题。我想使用类节点和类边制作一棵树,如下所示;

template <typename EdgeT>
class node
{
public:
    std::vector<EdgeT> edge_out;
    std::vector<EdgeT> edge_in;
};


template <typename NodeT>
class edge
{
public:
    NodeT* src;
    NodeT* dst;
    int weight;
};


template <typename NodeT, typename EdgeT>
class graph
{
public:
    std::vector<NodeT> nodes;
};

我发现我不能声明图形类 ex:

graph< node, edge > g; // <--- this cannot be solved 

graph< node< edge <node.....>, edge< node< edge>>  >  //it makes infinity declaration..

如何重新定义类的结构?

最佳答案

这是一种方法:

#include <vector>

template<template<typename NodeT,typename T>class EdgeT, typename T=double>
struct Node {
   typedef Node<EdgeT,T> self_type;
   typedef EdgeT<self_type, T> edge_type;
   std::vector<edge_type> edge_out;
   std::vector<edge_type> edge_in;
   T data;
};

template<typename NodeT,typename T>
struct Edge {
   typedef NodeT node_type;
   node_type* src;
   node_type* dst;
   int weight;
};

template<typename NodeT, typename EdgeT=typename NodeT::edge_type>
struct graph {
   typedef NodeT node_type;
   typedef EdgeT edge_type;
   std::vector<NodeT> nodes;
};

int main() {
   typedef graph< Node<Edge> > graph_type;
   graph_type my_graph;
   my_graph.nodes.push_back( graph_type::node_type() );
   my_graph.nodes.push_back( graph_type::node_type() );
   my_graph.nodes.front().edge_out.push_back( {&my_graph.nodes[0], &my_graph.nodes[1], 1} );
   my_graph.nodes.back().edge_in.push_back( {&my_graph.nodes[0], &my_graph.nodes[1], 1} );
}

对于另一种方法,您可以查看 boost::variant 如何处理递归变体。

解决这个问题的另一种方法会更正式。 C++ 模板元编程是一种函数式语言——函数式编程中有多种技术可以用来描述无需前向声明的递归结构。

我敢打赌某种定点组合器可能会起作用,但我无法弄清楚它是如何起作用的。 :)

关于c++ - 圆形模板引用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15330073/

相关文章:

c - 缺少删除 sll 最后一个节点的情况

java - 如何修复 Eclipse 项目的结构?

c - 通过函数+结构体读取文件

c++ - cURL 是一个网络库吗?

c++ 使用过多的 cpu

c++ - 为什么更喜欢基于模板的静态断言而不是基于 typedef 的静态断言?

c++ - 在模板类中使用 r 和 l 值构造函数时出错

c++ - 偏特化的默认参数

c++ - 我如何获取指向通用引用的指针?

c++ - Boost.MultiIndex 模板替换失败?