我有 2 个类 ConstVisitorBase
和 VisitorBase
,其中包含一些用于访问对象的代码。例如:
struct Node
{
enum class Type { ... };
Type type;
}
class ConstVisitorBase
{
public:
virtual void VisitType1( Node const & node );
...
private:
void VisitNode( Node const & node )
{
switch( node.type )
{
case Node::Type::type1: VisitType1( node );
}
...
}
}
class VisitorBase
{
public:
virtual void VisitType1( Node & node );
...
private:
void VisitNode( Node & node )
{
switch( node.type )
{
case Node::Type::type1: VisitType1( node );
}
...
}
}
除了 const
说明符之外,私有(private)方法 VisitNode
的代码是相同的。
有没有办法避免这种重复?
即使涉及多个方法( VisitNode
调用 EnterNode
和 LeaveNode
)?
最佳答案
由于 VisitType1
是公共(public)的,并且这两个类不相关,因此您可以使用模板函数:
template<typename Visitor, typename T>
void dispatch_visits(Visitor& visitor, T&& node){
switch( node.type )
{
case Node::Type::type1: visitor.VisitType1( node );
}
...
}
关于c++ - 如何避免访问者和 const 访问者基类中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72948090/