如何摆脱vistUpper,visitDowner,visitX ...函数中的代码重复?它们之间唯一的不同是创建新的WhateverAction(params)

我可以使用startVisit和endVisit函数来减少重复的长度,但是重复仍然存在...我希望可以有一种更优雅的方法?

    virtual void visitUpper(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new UpperAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    virtual void visitDowner(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new DownerAction(potion);
        actions.push_back(action);
        // add to our button list
    }
    //    ... and some more visitX which are identical except new XAction ...
    void actOn(int actionIndex)
    {
        actions[actionIndex]->prepareDrink();
    }

最佳答案

您可以在类里面尝试以下方法:

private:
    template<typename T>
    void visit(const Potion& potion)
    {
        // leave if unavailable action for various reasons
        // and a few more things...
        PotionAction* action = new T(potion);
        actions.push_back(action);
        // add to our button list
    }

 public:

    virtual void visitUpper(const Potion& potion)
    {
        visit<UpperAction>(potion);
    }
    virtual void visitDowner(const Potion& potion)
    {
        visit<DownerAction>(potion);
    }
    // more visitXXX ...

10-08 04:06