简体   繁体   English

在C ++中过滤类型名称

[英]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? 是否可以过滤类型名称? Eg I want to allow only uint8_t, int8_t, uint16_t, int16_t etc. + float and double too ? 例如,我只想允许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. 我不想做10条if语句,因为它看起来不太干净。

You can do this using std::is_integral and SFINAE. 您可以使用std::is_integral和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 相反,如果要允许所有整数和浮点类型,则可以使用std::is_arithmetic

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

It seems you need a function that accept only any integral types. 似乎您需要一个仅接受任何整数类型的函数。

There is an existing type trait for that un the <type_traits> header called std::is_integral . <type_traits>头存在一个名为std::is_integral类型特征。 You can use it with std::enable_if to produce the expected constraint: 您可以将其与std::enable_if以产生预期的约束:

template<typename T, std::enable_if_t<std::is_integral<T>::value, int> = 0>
void put(T value) {
    constexpr 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]);
        }
    }
}

Your function is now not callable with non integral types. 现在,您的函数不可用于非整数类型。

Be aware that if there's another overload of the function, the compiler will try it too. 请注意,如果该函数还有另一个重载,编译器也会尝试。 That means that if you have another function that accept any floating types, the compiler will select the appropriated overload. 这意味着,如果您有另一个接受任何浮点类型的函数,则编译器将选择适当的重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM