根据模板参数添加成员函数和成员变量

use*_*717 6 c++ templates sfinae template-specialization c++17

我有一系列函数{f_n},它们f_0是连续的,f_1是连续可微的,$ f_ {n} \在C ^ {n} [a,b] $等等.我有一个C++类,f_n通过向量上的查找表给出数值评估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;
};
Run Code Online (Sandbox Code Playgroud)

但是,如果f是可区分的(n >= 1),我想添加一个成员函数:

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;
};
Run Code Online (Sandbox Code Playgroud)

我还想为n> = 2添加第二个派生成员,依此类推.这可以在一个班级完成吗?(C++ 17语法对我来说是可以接受的.)

Bar*_*rry 5

对于每个n > 0,我们添加一个新的成员函数,将该值作为从下一个级别继承的参数:

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;
};
Run Code Online (Sandbox Code Playgroud)

其中基本版本添加了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;
};
Run Code Online (Sandbox Code Playgroud)

这意味着一阶导数调用prime(x, integral_constant<int, 1>{}),二阶导数调用prime(x, integral_constant<int, 2>{}),等等。