2017-12-13 32 views
0

일련의 숫자를 생성하는 코드가 있으며 해당 숫자에 대해 다른 온라인 후 처리 작업을 수행하려고합니다. 그래서 같이,이를 달성하기 위해 정책 기반 설계를 사용하는 것을 시도하고있다 :C++ - 템플릿 정책 클래스로 오버로드

// 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); 
} 

그래서 내 질문은 : 어떻게 IntegratorPolicy에 의해 정의 된 방법 addValue를 호출하는 코드를받을 수 있나요?

p.s. 나는 C++ 98을 사용해야한다.

+0

정적 인 방식으로 비 정적 함수를 호출하려는 것처럼 보입니다. – UKMonkey

답변

0

좋아, 나는 그것을 생각하고 스스로 해결책을 찾았습니다. 문제는 실제로 어리 석다는 것을 깨닫게하지만 누군가 다른 사람이 그 문제에 빠질 때 게시 할 것입니다. 내부 OutputQuantity 내가 명시 적으로 IntegratorPolicy::addValue을 호출하기 위해 addValue을 오버로드하여 기본적으로 래퍼 기능을 작성했습니다.