cubicSplineFunction; // ... here be some additional code to populate t-6ren">
gpt4 book ai didi

c++ - 表示 "something callable with particular signature"的模板参数

转载 作者:行者123 更新时间:2023-11-28 01:34:05 24 4
gpt4 key购买 nike

我希望能够编写这样的代码:

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 ...

最佳答案

template<class F, class R=std::result_of_t<F&(S const&)>>
SplineFunction<R> transform(F f) const

不要显式传递类型;让他们被推导出来。

typename std::result_of<F&(S const&)>::type .

衰减 R 类型(如 std 衰减)也可能很聪明,因为 SplineFunction 存储其模板参数,衰减使类型更适合存储。

关于c++ - 表示 "something callable with particular signature"的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com