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

标签 c++ c++11 templates lambda

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

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/

相关文章:

c++ - 编译大型头文件 C++

c++ - 使用模板别名、继承模板和使用 "template parent' s"types 时编译错误

c++ - 为什么在部分特化中不能推导从属模板类型?

c++ - epoll等待修改文件描述符集

c++ - N 位环绕的整数减法

c++ - std::to_string 线程安全吗?

c++ - 指向 C 样式数组元素的指针的 const vector

c++ - 非静态引用成员 ‘int& Property<int>::value’ ,不能使用默认赋值运算符

c++ - 为不同版本的函数模板识别不同的默认参数

c++ - 部分特化可以在特化的参数列表中引用 sizeof(T) 吗?