Usage of enable_if

std::enable_if is a template class in the C++ standard library, used to select template overloads or disable specific functions based on conditions at compile time.
The basic usage of std::enable_if is to use it in the return type of a function template and perform conditional judgment combined with type characteristics. If the condition is true, the return type will be the specified type, otherwise, the overload will be disabled.

Use of std::enable_if

template <typename T>
typename std::enable_if<Condition, ReturnType>::type FunctionName(Parameters...)
{
    
    
    // 函数体
}

Among them, define the conditions that need to be met (for example, type characteristics or type comparison, etc.) in the first template parameter of enable_if. If the condition is true, the return type will be ReturnType, otherwise the function will be disabled.
Here are a few examples of different uses of std::enable_if:

Use type to determine

#include <type_traits>

template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
FunctionName(T value)
{
    
    
    // 函数体,仅适用于整数类型
}

Use type comparison judgment

template<typename T, typename U>
typename std::enable_if<std::is_same<T, U>::value, void>::type
FunctionName(T value1, U value2)
{
    
    
    // 函数体,仅适用于T和U相同的类型
}

Use multiple conditions to combine judgments

template<typename T>
typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, bool>::type
FunctionName(T value)
{
    
    
    // 函数体,仅适用于有符号整数类型
}

Official website information:

https://en.cppreference.com/w/cpp/types/enable_if

Guess you like

Origin blog.csdn.net/neuzhangno/article/details/132204096