0

I want to write a template function to interpolate missing values within a std::map like this :

template<typename T1, typename T2>
T2 interpolate(const std::map<T1, T2> &data, const T1 at_x);

When I write the function with real type for the map, like std::map <unsigned short, double> , all is fine. But when I want to template the function, after I create an iterator for the map, I cannot access the ->first and ->second membres anymore from the iterator ? why ?

Here's the code of my templated function:

template<typename T1, typename T2>
T2 interpolate(const std::map<T1, T2> &data, const T1 at_x){

    typedef std::map<T1, T2>::const_iterator i_t;

    i_t right = data.upper_bound(at_x);
    i_t left;
    double delta;

    data.begin()->first; // this is ok for the compiler and the auto-completion of eclipse
    right->first; // this is rejected: "Field 'first' could not be resolved"

    // after range of keys in map:
    if (right == data.end()) {
        --right;
        left = right;
        --left;
        delta = ((double)at_x - left->first) / (right->first - left->first);
        return right->second + (delta - 1.0) * (right->second - left->second);
    }

    // before range of keys in map:
    if (right == data.begin()) {
        left = right;
        ++left;
        delta = ((double)at_x - left->first) / (right->first - left->first);
        return right->second + (delta - 1.0) * (right->second - left->second);
    }

    // within range of keys in map:
    left = right;
    --left;
    delta = ((double)at_x - left->first) / (right->first - left->first);
    return delta * right->second + (1.0 - delta) * left->second;
}

Many thanks for any help.

Samuel

Samuel
  • 19
  • 4
  • 1
    `typedef typename std::map::const_iterator i_t;` ! – Piotr Skotnicki Apr 06 '16 at 17:20
  • 1
    Possible duplicate: [Where and why do I have to put the “template” and “typename” keywords?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – NathanOliver Apr 06 '16 at 17:26
  • arrrrrrrrrrrrrrrr ! perfect answer ! what a mistake I made ! Many Thanks Piotr ! – Samuel Apr 06 '16 at 17:27
  • With all due respect, I think that this question was closed in error. The supposed duplicate is "Where and why do I have to put the “template” and “typename” keywords?" which does not have a c++11 tag, as this question does. While the problem is the same as the one there, the solutions are not necessarily the same (e.g., using `decltype`). – Ami Tavory Apr 06 '16 at 17:47
  • @AmiTavory, I agree with your observation, but the proper thing to do is to add this as an aswer to the duplicate so it becomes an authoritive answer in both dialects. – SergeyA Apr 06 '16 at 19:56

0 Answers0