C ++ - 使用模板策略类

时间:2017-12-13 10:07:58

标签: c++ templates override policy c++98

我有一个生成一系列数字的代码,我想对这些数字进行不同的在线后处理。我试图使用基于策略的设计来实现这一点,如下所示:

// This is a general class to integrate some quantity
class QuantityIntegrator
{
public:
    QuantityIntegrator () : result(0) {}
    double getResult() const {return result;}
    void setResult(const double val) {result = val;}

private:
    double result;
};

// This is my policy class
// A dummy integrator for this example, but there can be others for
// arithmetic average, root-mean-square, etc...
struct NoIntegrator : public QuantityIntegrator
{
    // The function that characterizes a policy
    void addValue(double val, double) {setResult(val);}
};

// Interface
// This is needed because I want to create a vector of OutputQuantity, which
// is templated
class OutputQuantity_I
{
public:
    // These are the functions that I want to override
    virtual double getResult() const {cout << "Calling forbidden function getResult"; return -123456;}
    virtual void addValue(double, double) {cout << "Calling forbidden function addValue";}

    // A method that produces some number sequence
    double evaluate() const
    {
        return 1;
    }
};

// The general class for output quantities, from which concrete output
// quantities will inherit
template <typename IntegratorPolicy>
struct OutputQuantity : public OutputQuantity_I,
                        public IntegratorPolicy
{
};

// One particular output quantity, whose template I can specialize to decide
// how to integrate it
template <typename IntegratorPolicy>
struct SomeOutput : public OutputQuantity<IntegratorPolicy>
{
};

typedef std::vector<OutputQuantity_I*> OutputQuantityList;


int main()
{
    SomeOutput s;
    OutputQuantityList l;
    l.push_back(&s);

    // Here OutputQuantity_I::addValue is called, instead of
    // IntegratorPolicy::addValue
    l[0]->addValue(1,2); 
}

所以我的问题是:如何让代码调用addValue定义的方法IntegratorPolicy

P.S。我一定会使用C ++ 98。

1 个答案:

答案 0 :(得分:0)

好的我给了它一个想法并自己找到了解决方案。它让我意识到这个问题实际上是愚蠢的,但我会发布它,因为其他人可能遇到它。在OutputQuantity内部,我覆盖addValue以显式调用IntegratorPolicy::addValue,编写基本上是包装函数的内容。