Code duplication prevention for different data types (uint16_t / uint32_t)

I am looking for an opportunity to use a function where I pass a pointer to the values ​​of uint16_t or uint32_t.

I am currently using two overloaded functions

std::vector<float> calcMap(uint16_t* map)
std::vector<float> calcMap(uint32_t* map)

Since they return floating point values, the calculation is the same for 16 and 32 bit values. The only difference is the data type that is required to traverse the specified array. I do not want all the content of the function twice, is there any way to make it independent of type?

+4
source share
2 answers

Mainly for completeness:

- . . :

  • :

    template<typename T> std::vector<float> calcMap(T*);
    extern template std::vector<float> calcMap<>(uint16_t*);
    extern template std::vector<float> calcMap<>(uint32_t*);
    
  • :

    template<typename T>
    std::vector<float> calcMap(T*) {
      // Now we implement
    }
    
    template std::vector<float> calcMap<>(uint16_t*); // Now this will link
    template std::vector<float> calcMap<>(uint32_t*); // As will this
    

drescherjm ? . , , , .

+4

uint16_t uint32_t, :

template <class T,
  class = typename std::enable_if<
    std::is_same<typename std::decay<T>::type, uint16_t>::value || 
    std::is_same<typename std::decay<T>::type, uint32_t>::value>::type>
std::vector<float> calcMap(T * map) {
  // Code
}

#include <type_traits> ++ 11 .

, , T * T const * . , T const * const, .

std::is_integral, , .

+4

Source: https://habr.com/ru/post/1687822/


All Articles