圆形模板参考结构 [英] Circular template reference structure

查看:46
本文介绍了圆形模板参考结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ploblem about circular template reference. I want to make a tree using class node and class edge as following;

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:

I found that I cannot declare graph class ex:

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

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

如何重新定义类的结构?

How can I redefine the structure of the classes?

推荐答案

这是一种方法:

#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 如何处理递归变体.

for another approach, you could look at how boost::variant handles recursive variants.

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

Another way to approach this would be more formal. C++ template metaprogramming is a functional language -- there are various techniques from functional programming in order to describe recursive structures without forward declaration that can be used.

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

I'm betting a fixed point combinator of some kind might work, but it is beyond me to figure out how. :)

这篇关于圆形模板参考结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆