Search code examples
c++templatesreinterpret-casttypename

Filter typenames in C++


This is my converter to byte array (vector).

template<typename T>
void put(T value) {
    int size = sizeof(value);

    uint8_t *array;
    array = reinterpret_cast<uint8_t *>(&value);

    if (littleEndian) {
        for (int i = 0; i < size; i++) {
            arr.push_back(array[i]);
        }
    } else {
        for (int i = size - 1; i >= 0; i--) {
            arr.push_back(array[i]);
        }
    }
}

As you can see, this function accepts all variable types. Is it possible to filter typenames? E.g. I want to allow only uint8_t, int8_t, uint16_t, int16_t etc. + float and double too? I don't want to make 10 if statements, because it doesn't look clean.


Solution

  • You can do this using std::is_integral and SFINAE. This will remove the template from consideration if the type is not a integer type. It would look something like

    template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
    void put(T value)
    {
        // code
    }
    

    Live Example

    If instead you want allow all integral and floating point types then you can use std::is_arithmetic like

    template<typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
    void put(T value)
    {
        // code
    }