C++模板问题

3
我正在尝试开发两个类,NodeConnection,但我没有C++或C++模板的经验。
Node包含连接列表,而Connection包含2个节点。因此,我认为节点具有指定列表中哪种类型的连接的模板参数,并且连接具有指定它所包含的节点的种类的模板参数。
在C ++中如何强制节点包含通用类型的连接,但这些连接包含Node类的节点?对于Connection类也是同样的问题。我想为节点的类型设置一个通用参数,但这些通用节点必须包含Connection类的连接列表。
我尝试了几种方法,以下是我目前拥有的:
template <template <template <class Conn> class Node> class Conn>
class Node {
};

有人能帮我吗?

提前感谢,

Jef

1个回答

3
假设您想要不同类型的节点,但连接只是两个节点之间的链接(也就是说,您不需要对连接进行任何特殊化),那么您可以这样做:
template <class Node>
class Connection
{
    Node& node1;
    Node& node2;
};

template <class Node>
class NodeBase
{
    std::list< Connection<Node> > connections;
};

// example concrete node
class MassNode : public NodeBase<MassNode>
{
    // stuff that makes a mass node more than just a node.
}

这是一种叫做奇妙递归模板模式的设计模式。
还有其他攻击这个问题的方法 - 你能否提供关于你特定问题领域的更多信息?
编辑以显示侵入性和非侵入性技术。
namespace intrusive
{
    template <class node>
    class directedConnection
    {
        node& From;
        node& To;
    };

    template <class node>
    class directedGraphNode
    {
    private:
        std::set< directedConnection<node>* > OutgoingConnections;
        std::set< directedConnection<node>* > IncomingConnections;
    };

    // sample concrete class. Note that it is a graph node AND it contains the node data.
    class bayesianNetworkNode : public directedGraphNode<bayesianNetworkNode>
    {
    public:
        double Probabilities[16];
    };

    bayesianNetworkNode B1, B2, B3;
}

namespace non_intrusive
{
    template <class T>
    class undirectedGraphNode;

    template <class T>
    class undirectedConnection
    {
        undirectedGraphNode<typename T>& Node1;
        undirectedGraphNode<typename T>& Node2;
    };

    template <class T>
    class undirectedGraphNode
    {
    private:
        std::set< undirectedConnection<T>* > Connections;
        T Value;
    public:
        T& operator * () { return Value; }
        T* operator -> () { return &Value; }
    };

    // sample concrete class. Note that this class contains the node data, but is NOT actually a graph node itself.
    // It is "pointed to" by a node in the same way that an STL iterator "points to" a collection item.
    class markovNetworkNode
    {
    public:
        std::set<formula> Formulae;
    };

    undirectedGraphNode<markovNetworkNode> M1, M2, M3;
}

谢谢!我想建模贝叶斯和马尔可夫网络。因此,一个具体的节点可以是一个随机变量,例如,连接可以是有向或无向的。因此,我还需要对Connection类进行特殊化处理...我该如何解决这个问题? - hermi
在我出门的路上 - 待会儿回来带两种技术 - 一种是侵入式的(就像上面的代码),另一种则不是。 - Gavi Lock
+1 很好的回答。简洁明了,功能齐全。而且完全通用。 - ralphtheninja
已编辑以展示有向和无向网络示例。并展示了侵入式(每个节点包含其业务级数据以及参与图形)和非侵入式(用于存储每个节点业务数据的类不知道它包含在图形中的事实)之间的区别。后一种技术被许多通用容器使用,特别是STL。 - Gavi Lock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接