lundi 5 octobre 2015

Null object pattern and functions

I'm trying to implement null object pattern for tree traversal. For now it looks like this and this doesn't work. How can i implement it? Thanks.

struct Node
{
    Node *_left;
    Node *_right;

    string _value;
};

struct Sentinel : Node
{
    static Sentinel Stop;
    typedef Node NodeType;
};

Sentinel Sentinel::Stop;

template<class T>
auto traverse(T *root) -> decltype(typedef T::NodeType, void)
{
    cout << "sentinel" << endl;
}

template<class T>
void traverse(T *root, ...)
{
    traverse(root->_left);
    traverse(root->_right);
}

int _tmain(int argc, _TCHAR* argv[])
{
    Node rightLeft{ &Sentinel::Stop, &Sentinel::Stop, "rightLeft" };
    Node left{ &Sentinel::Stop, &Sentinel::Stop, "left" };
    Node right{ &rightLeft, &Sentinel::Stop, "right" };
    Node root{ &left, &right, "root" };
    traverse(&root);

    return 0;
}

EDIT: It goes into neverending recursion.

Aucun commentaire:

Enregistrer un commentaire