Reputation: 90
I'm trying to write a function which can receive an iterator of std::pair (points along a curve) which can do linear interpolation for a given X and return Y.
A function signature similar to this would be great, but I can't figure out how to set up the template definition.
template<class RandomAccessIterator, typename X, typename Y >
Y piecewiseLinearInterpolate(
RandomAccessIterator begin,
RandomAccessIterator end,
X x);
However, doing this results in template argument deduction/substitution failing.
This also fails to compile:
template<class RandomAccessIterator, template <class X, class Y> class std::pair >
constexpr Y piecewiseLinearInterpolate(
RandomAccessIterator begin,
RandomAccessIterator end,
X x);
I have gotten a function with the following function signature to work, but it requires me to specify the types contained in the pair.
using AdcCount16 = uint16_t;
using Pressure = int;
template<class RandomAccessIterator>
Pressure piecewiseLinearInterpolate(
RandomAccessIterator begin,
RandomAccessIterator end,
AdcCount16 x);
How can I write a generalized function which can receive a random access iterator of std::pair and a value of type X which returns a value of type Y?
Edit:
I am calling the function like this:
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);
Upvotes: 1
Views: 84
Reputation: 119847
You want something like this
template<class RandomAccessIterator>
auto piecewiseLinearInterpolate(
RandomAccessIterator begin,
RandomAccessIterator end,
decltype(begin->first)) ->
decltype(begin->second);
Upvotes: 3