我希望能够编写这样的代码:
SplineFunction<Polynomial<3>> cubicSplineFunction;
// ... here be some additional code to populate the above object ...
auto dydx = cubicSplineFunction.transform<Polynomial<2>>(const Polynomial<3>& cubicSpline){
return cubicSpline.derivative();
};
auto dsdx = cubicSplineFunction.transform<T/*?*/>([](const Polynomial<3>& cubicSpline){
Polynomial<2> dy = cubicSpline.derivative();
Polynomial<4> dsSquared = dy*dy + 1*1;
return [dsSquared](double x){ // Fixed in response to comment: capture by value
return std::sqrt(dsSquared);
};
});
dydx(1.0); // efficient evaluation of cubicSplineFunction's derivative
dsdx(2.0); // efficient evaluation of cubicSplineFunction's arc rate
所以我实现了下面的类。但是我应该用什么类型替换上面的T
(第8行)来表示“可以用签名double(double)
调用的东西”?
template<typename S>
struct SplineFunction {
std::vector<S> splines;
auto operator()(double t) const {
int i = static_cast<int>(t);
return splines[i](t - i);
}
template<typename R, typename F>
SplineFunction <R> transform(F f) const {
SplineFunction <R> tfs;
for (const auto& s : splines) {
tfs.splines.push_back(f(s));
}
return tfs;
}
// ... MORE CODE ...
}
template<int N>
struct Polynomial {
std::array<double, N+1> coeffs;
double operator()(double x) const;
Polynomial<N - 1> derivative() const;
// ... MORE CODE ...
}
template<int L, int M>
Polynomial<L+M> operator*(const Polynomial<L>& lhs, const Polynomial<M>& rhs);
template<int L>
Polynomial<L> operator+(Polynomial<L> lhs, double rhs);
// ... MORE CODE ...
答案 0 :(得分:2)
template<class F, class R=std::result_of_t<F&(S const&)>>
SplineFunction<R> transform(F f) const
不要传递明确的类型;让他们推断出来。
在c++11执行typename std::result_of<F&(S const&)>::type
。
衰减R类型(如在std衰变中)也可能是智能的,因为SplineFunction存储其模板参数,而decay使类型更适合存储。