enable_if template programming implements byte order conversion template

enable_if and SFINAE

SFINAE is a feature of the template, that is, no error is reported if the replacement fails.

Normally, when a function is matched, it matches the defined overloaded functions in order of priority, and finally selects the best matching function to run.
The template is the same, but when replacing the template, even if an abnormal error occurs, it is not considered an error, but simply passed.

enable_if is a standard template of C++, its implementation is very simple, here we give a way of its implementation:

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };
Its function is that when bool is true, enable_if will have a type type, and when it is false, it will not.
Therefore, when this condition is true, there is a type, and when the condition is false, there is no type. Combined with the SFINAE feature, it is more convenient to make a small error in the template, so that the template parsing skips the current template.

endian conversion

template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
byteswap(T value) {
    return (T)bswap_64((uint64_t)value);
}

/**
 * @brief 4字节类型的字节序转化
 */
template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint32_t), T>::type
byteswap(T value) {
    return (T)bswap_32((uint32_t)value);
}

/**
 * @brief 2字节类型的字节序转化
 */
template<class T>
typename std::enable_if<sizeof(T) == sizeof(uint16_t), T>::type
byteswap(T value) {
    return (T)bswap_16((uint16_t)value);
}
When matching the byteswap template function, the return value
std::enable_if<sizeof(T) == sizeof(uint64_t), T>::type
will judge whether the byte number of T is equal to 8, when it is equal to 8, enable_if has type type, the function The template replacement is successful, and when the execution function
is not equal to 8, there is no enable_if and no type type, and the replacement is wrong, but no error will be reported and the template will be skipped and continue to match downwards.

reference:

Video: New C++ Standard 012: enable_if

Blog: Use of C++ enable_if_jeffasd's Blog-CSDN Blog_c++ enable_if

Guess you like

Origin blog.csdn.net/qq_55796594/article/details/129213616