I want to implement the visitor pattern for one of my class without having to depend on the types that will implement the interface to visit them.
My solution was this:
class model::VisitableNode {
public:
template<class T>
virtual T accept(NodeVisitor<T>);
}
But C++ says that it doesn't support template + virtual methods
Node in my application will have only one implementation but if I don't use a template return type my model class will depend on the toolkit that I'm using to create the graphic for my app.
If a visitor needs to return a value, it is normal to store the returned value in the visitor itself. Thus:
NodeVisitor<double> dv;
node->accept(dv);
double result = dv.result();
If you don't like the boilerplate, you can wrap it in a non-virtual member:
class model::VisitableNode {
public:
template<class T>
/* non-virtual */ T accept(NodeVisitor<T>& v) {
do_accept(v);
return v.result;
}
virtual void do_accept(NodeVisitorBase& v) = 0;
}
Why not template the class itself?
template<class T>
class model::VisitableNode<T> {
public:
virtual T accept(NodeVisitor<T>);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.