c++ - 如何避免访问者和 const 访问者基类中的代码重复

标签 c++ software-design code-duplication

我有 2 个类 ConstVisitorBaseVisitorBase,其中包含一些用于访问对象的代码。例如:

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 调用 EnterNodeLeaveNode )?

最佳答案

由于 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/

相关文章:

c++ - 从函数 C++ 打印出二维数组

c++ - 将两个字节转换为 12 位短值?

c++ - Qt 获取不同操作系统的默认样式表

oop - 为什么封装是 OOP 语言的一个重要特征?

software-design - 如何处理对软件中荒谬功能的请求?

c++ - 如何合并两个具有相同代码但在不同结构上运行的类

c++ - 在 boost BGL 中使用 make_bfs_visitor 而不是带有 BFS 的派生访问者

python - 使用百分比计算 : decimal or readable?

kotlin - 当使用两个包含相同类文件的 SDK 的 .aar 文件时,如何在 Kotlin 中解决这个重复的类?

c++ - 如何删除类似的 const 和非常量成员函数之间的代码重复?