简体   繁体   English

C ++中的模板和继承

[英]Templates and inheritance in C++

I am trying to set up class hierarchy as follows: 我试图建立类层次结构,如下所示:

template< class TProcess>
class Path
{
protected:
    TProcess &process;
    double Xt;
public:
    Path(TProcess &process, double X0) : process(process), Xt(X0) {}
    virtual ~Path(){}

    virtual double dX(double dt, const std::vector<double> &dW) = 0;
};

template< class TProcess>
class Process
{
protected:
    double X0;
public:
    Process(double X0) : X0(X0) {}
    virtual ~Process(){}

    virtual boost::shared_ptr<Path<TProcess> > NewPath() =0;
};

but then I found it impossible to declare subclasses so that it works. 但是后来我发现不可能声明子类以使其起作用。 I tried: 我试过了:

class GeometricBrownianMotion;
class GBMPath: public Path<GeometricBrownianMotion>
{
    double dX(double dt, const std::vector<double> &dW)
    {
        Xt = Xt*exp(process.mu*dt - 0.5*dt + process.sigma*dW);
        return Xt;
    }
};

class GeometricBrownianMotion: public Process<GeometricBrownianMotion>
{
    double mu;
    const std::vector<double> &sigma;
    double sigma2;
public:
    GeometricBrownianMotion(double X0, double mu, const std::vector<double> &sigma): Process(X0), mu(mu), sigma(sigma), sigma2(sigma*sigma)
    {}

    virtual boost::shared_ptr<Path<GeometricBrownianMotion> > NewPath()
    {
        return boost::shared_ptr<Path<GeometricBrownianMotion> >(new GBMPath(*this, X0));
    }

};

but I get the following error: 但我收到以下错误:

process.h:58: error: forward declaration of ‘struct GeometricBrownianMotion’
process.h:63: error: invalid use of incomplete type ‘struct GeometricBrownianMotion’

Any ideas how to make it work? 有什么想法使它起作用吗?

Just separate your implementation from your class definitions, and the problem will go away nearly automatically. 只需将您的实现与类定义分开,问题就会几乎自动消失。

Nearly, because you might just want to move the definition of GeometricBrownianMotion before using it as a template parameter. 几乎是因为您可能只想移动GeometricBrownianMotion的定义,然后再将其用作模板参数。

EDIT: even not nearly, at least on my compiler, removing all inline methods definitions was just enough to get it to compile. 编辑:至少在我的编译器上,即使不是几乎全部,删除所有内联方法定义也足以使其进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM