【问题标题】:How to write a templated function that uses iterators and specific types如何编写使用迭代器和特定类型的模板化函数
【发布时间】:2019-08-13 04:01:48
【问题描述】:

我正在尝试编写一个函数,它可以接收 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 的随机访问迭代器和返回 Y 类型值的 X 类型值?

编辑:

我这样调用函数:

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);

【问题讨论】:

  • 您能否提供一些代码来展示您如何使用不为您编译的模板?问题可能在于您如何使用模板而不是定义。
  • 使用 Itr = std::pair::iterator;模板 Y pieceWiseLinearInterpolate (Itr begin, Itr end, X x); ---> 这不能解决你的问题吗?
  • 我提供了一个如何使用该功能的示例。 Rajkumar,这不适合我。

标签: c++ templates iterator


【解决方案1】:

你想要这样的东西

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

【讨论】:

  • 有什么理由去掉最后一个参数的名称?
  • @generic_opto_guy 在原型中不需要,在实际实现中显然需要
猜你喜欢
  • 2020-09-28
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2012-06-19
  • 2012-12-26
  • 2021-08-21
  • 2012-04-01
相关资源
最近更新 更多