Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add member functions and member variables based on template argument

I have a family of functions {f_n} where f_0 is continuous, f_1 is continuously differentiable, $f_{n} \in C^{n}[a,b]$ so on. I have a C++ class which gives a numerical evaluation of f_n via a lookup table on a vector v

template<int n, typename Real=double>
class f
{
public:
    f() { /* initialize v */ }

    Real operator()(Real x) { /* find appropriate index for x, and interpolate */}

private:
    std::vector<Real> v;
};

However, if f is differentiable (n >= 1), I want to add a member function:

template<int n, typename Real=double>
class f
{
public:
    f() { /* initialize v and dv */ }

    Real operator()(Real x) { /* find appropriate index for x, and interpolate on v */}

    Real prime(Real x) { /* find appropriate index for x, and interpolate on dv */}

private:
    std::vector<Real> v;
    std::vector<Real> dv;
};

I would also like to add a second derivative member for n >= 2, so on. Can this be done in a single class? (C++17 syntax is acceptable for me.)

like image 841
user14717 Avatar asked Mar 01 '19 20:03

user14717


Video Answer


1 Answers

For each n > 0, we add a new member function taking that value as an argument that inherits from the next level down:

template<int n, typename Real=double>
class f
    : public f<n-1, Real>
{
public:
    f() { /* initialize dv */ }

    using f<n-1, Real>::prime;
    Real prime(Real x, integral_constant<int, n>) { 
        /* find appropriate index for x, and interpolate on dv */
    }

protected:
    std::vector<Real> dv;
};

Where the base version adds the operator():

template<typename Real=double>
class f<0, Real>
{
public:
    f() { /* initialize v */ }

    Real operator()(Real x) { /* find appropriate index for x, and interpolate */}
    Real prime(Real x) { return (*this)(x); }

protected:
    std::vector<Real> v;
};

This means that the first derivative calls prime(x, integral_constant<int, 1>{}), the second derivative calls prime(x, integral_constant<int, 2>{}), etc.

like image 121
Barry Avatar answered Oct 19 '22 06:10

Barry