Boost logo

Boost Users :

From: Timothy Ritchey (tritchey_at_[hidden])
Date: 2004-10-22 09:49:48


I have an interpreter that uses a visitor pattern while performing a
reduction of the program tree. As part of the visitor pattern, each
class that can be a node in the tree must respond to:

virtual void accept(Visitor& v);

where each node then implements by calling visitor with itself using
the proper type. The function calls in visitor are like:

void visit(shared_ptr<Node> node);
void visit(shared_ptr<Type> node);
etc.

(where Type is a descendant of node BTW).

Normally with the visitor pattern (GOF style in this case), the
implementation of accept is simply:

void Node::accept(Visitor &v) {
        v.visit(this);
}

I've tried adding enable_shared_from_this<...> as a superclass of my
nodes, and returning shared_from_this(), which works in some cases, but
in others just seems to hang. These occur in classes that are a little
more complex. For example, I have a TypeTemplate<T> class that wraps to
underlying types TypeTemplate<int>, TypeTemplate<float>,
TypeTemplate<etc>. I've tried adding
enable_shared_from_this<TypeTemplate<T> >, and then having an
implmentation

void TypeTemplate<T>::accept(Visitor &v) {
v.visit(enable_shared_from_this<TypeTemplate<T> >::shared_from_this());
}

but it just hangs on both vc7.1 on windows and Xcode on OS X. (I had to
add the extra scoping because I got complaints that "shared_from_this()
was ambiguous in multiple inheritance.")

I read in some past postings that the shared_from_this template doesn't
work so well for complex class hierarchies, and I am wondering if I am
running into that.

I was thinking of putting my own internal_weak_ptr into the classes,
but was confused by some of the examples I have seen. Most of them seem
to reference a static function create() which instantiates the
weak_ptr, and returns a shared_ptr<X>. When I consider my situation:

shared_ptr<Node> aNode(new Node(...));
Visitor v;
aNode->accept(v);

How does the accept implementation return a shared_ptr that is linked
with aNode? I've looked through the enable_shared_from_this
implementation, and can't figure out how it is supposed to work. even
if I return shared_from_this(), I'm not sure now that is linked to
aNode. Does everything have to go through a factory like create()?

Sorry for the long rambling e-mail. I hope it makes sense what I am
trying to do.

Cheers,
tim


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net