Map function should be templated

The map function says that it only works for long integers. It should have been defined as

template <typename T> 
   T map(T value,
    T in_min, T in_max, 
    T out_min, T out_max) {
  return (value – in_min) * 
            (out_max – out_min) / 
            (in_max – in_min) + out_min;

It seems odd to make a limitation that is not required by the language

There is some discussion on the subject here:

and related discussion on the issues that link off that.

Note Paul Stoffregen's comment:

we've been using a C++ template for map() on Teensy for quite some time. It turned to be quite a bit more complicated than the code above. Ultimately we ended up with 2 templates using type_traits and std:enable_if. When the input "x" is any integer type, you want to convert all 5 inputs to signed long. If you skip that step, problems with numerical range come up. When the input "x" is any floating point type, you want to convert the other 4 inputs to that type, so the whole thing is done in the same numerical precision as the input number.

I am not a template expert. I am glad that they exist. But they should have been called in during the design phase so "pure C" solutions would have been avoided. However, once the problem is known, an expert can update this (maybe with a new name). I've been using the simple template I showed for a couple years now, and, indeed, I have to be a bit careful about how I specify the argument, but it works well enough.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.