class
psc_f
{
public:
psc_f(double alpha) : alpha{ alpha } {}
double operator() (double x) const
{
return
sin(alpha
*
x)
+
cos(x);
}
private:
double alpha;
};
template <typename F, typename T>
class
derivative
{
public:
derivative(const F& f, const T& h) : f{ f }, h{ h } {}
T operator()(const T& x) const
{
return
(f(x
+
h)
-
f(x))
/
h;
}
private:
const F& f;
T h;
};
template <unsigned N, typename F, typename T>
class
nth_derivative
{
using prev_derivative
=
nth_derivative <N
-
1
, F, T>;
public:
nth_derivative(const F& f, const T& h) : h{ h }, fp{ f, h }
{}
T operator()(const T& x) const
{
return
N &
1
? (fp(x
+
h)
-
fp(x))
/
h
: (fp(x)
-
fp(x
-
h))
/
h;
}
private:
T h;
prev_derivative fp;
};
template <typename F, typename T>
class
nth_derivative<
1
, F, T>
: public derivative<F, T>
{
using derivative<F, T >::derivative;
};
int
main()
{
nth_derivative<
22
, psc_f, double> d22_psc_o{ psc_f(
1.0
),
0.00001
};
cout <<
"22nd der. of sin(x) + cos(x) at 0 is "
<< d22_psc_o(
0.0
)
<<
'\n'
;
}