如何避免多态?

时间:2018-11-06 18:26:53

标签: c++ design-patterns

我的数据类型为OperationSequence。下面是OperationSequence.h

class OperationSequence
{
public:
    void appendOperation(std::function<double(double)> operation);
    void moveOperation(int operation_index);
    void eraseOperation(int operation_index);

    const std::vector<std::function<double(double)>>& data() const;
private:
    std::vector<std::function<double(double)>> operation_sequence;
};

double executeSequence(const OperationSequence& operation_sequence, double value);
void executeSequence(const OperationSequence& operation_sequence, const std::string& file_name);

我必须实现printOperationSequence(const OperationSequence& operation_sequence).

工作分配将操作要求设为f: double -> double。还请求了某些操作,例如AdditionMultiplication。 显而易见的实现是创建接口Operation并使其可以用f: double -> double调用并具有std::string getName()方法。

OperationSequence保持这种通用性又使它以一种有意义的方式轻松而有效地打印出OperationSequence的好方法是什么?

有意义的方式类似于乘法,加法...

将构造委派给其他也会创建operation_name_sequence的类是一个好主意吗?

P.S。随时改进问题标题:D

1 个答案:

答案 0 :(得分:1)

如果您想避免具有多态性(即使std::function使用多态或类似方式进行类型擦除),则可以创建类Operation来为函数添加名称:

struct Operation
{
    std::string name;
    std::function<double(double)> f;
};

class OperationSequence
{
public:
    void appendOperation(const Operation& operation);
    void appendOperation(const std::string& name, std::function<double(double)> f);

    void moveOperation(int operation_index);
    void eraseOperation(int operation_index);

    const std::vector<Operation>& data() const;
private:
    std::vector<Operation> operations;
};

然后

void printOperationSequence(const OperationSequence& operation_sequence)
{
    for (const auto& op : operation_sequence.data()) {
         std::cout << op.name << std::endl;
    }
}