我正在尝试编写一个函数,该函数可以接收std::pair(沿曲线的点)的迭代器,该迭代器可以对给定的X进行线性插值并返回Y。

类似于这样的函数签名会很棒,但是我不知道如何设置模板定义。

template<class RandomAccessIterator, typename X, typename Y >
Y piecewiseLinearInterpolate(
    RandomAccessIterator begin,
    RandomAccessIterator end,
    X x);

但是,这样做会导致模板参数推导/替换失败。

这也无法编译:

template<class RandomAccessIterator, template <class X, class Y> class std::pair >
constexpr Y piecewiseLinearInterpolate(
    RandomAccessIterator begin,
    RandomAccessIterator end,
    X x);

我已经获得了一个具有以下函数签名的函数,但是需要我指定该对中包含的类型。

using AdcCount16 = uint16_t;
using Pressure = int;

template<class RandomAccessIterator>
Pressure piecewiseLinearInterpolate(
    RandomAccessIterator begin,
    RandomAccessIterator end,
    AdcCount16 x);

如何编写一个通用函数,该函数可以接收std::pair的随机访问迭代器和X类型的值,该值返回Y类型的值?

编辑:

我正在这样调用函数:

using PressurePoint = std::pair<AdcCount16, Pressure>;

PressurePoint piecewise[] = {
    {0, 1},
    {2, 3},
    {5, 9}
};

Pressure p1 = piecewiseLinearInterpolate(
    std::cbegin(piecewise),
    std::cend(piecewise),
    3);

assert(p1 == 5);

最佳答案

你想要这样的东西

template<class RandomAccessIterator>
auto piecewiseLinearInterpolate(
    RandomAccessIterator begin,
    RandomAccessIterator end,
    decltype(begin->first)) ->
               decltype(begin->second);

关于c++ - 如何编写使用迭代器和特定类型的模板化函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57470958/

10-11 23:05
查看更多