需要一个虚拟模板成员解决方法 [英] need a virtual template member workaround
问题描述
我需要编写一个实现访问者设计模式的程序。问题是基本访问类是一个模板类。这意味着BaseVisited :: accept()接受一个模板类作为参数,并且因为它使用'this',我需要'this'指向对象的正确运行时实例,它也需要是虚拟的。
我想知道是否有任何方法解决这个问题。
I need to write a program implementing the visitor design pattern. The problem is that the base visitor class is a template class. This means that BaseVisited::accept() takes a template class as a parameter and since it uses 'this' and i need 'this' to point to the correct runtime instance of the object, it also needs to be virtual.
I'd like to know if there's any way around this problem.
template <typename T>
class BaseVisitor {
public:
BaseVisitor();
T visit(BaseVisited *visited);
virtual ~BaseVisitor();
}
class BaseVisited {
BaseVisited();
template <typename T>
virtual void accept(BaseVisitor<T> *visitor) { visitor->visit(this); }; // problem
virtual ~BaseVisited();
}
推荐答案
class BaseVisited;
class BaseVisitorInternal {
public:
virtual void visit(BaseVisited*) = 0;
virtual ~BaseVisitorInternal() {}
};
class BaseVisited {
BaseVisited();
virtual void accept(BaseVisitorInternal* visitor) { visitor->visit(this); }
};
template<typename T> class BaseVisitor : public BaseVisitorInternal {
void visit(BaseVisited* visited);
};
如果你还需要BaseVisited的派生类模板,并传递他们正确的类型/重载访问,你正式死亡。
If you need BaseVisited's derived classes to be templated too AND pass their correct types/overloads to visit, you're officially dead.
这篇关于需要一个虚拟模板成员解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!