Template Function Specialization for Integer Types
c++, templates
Solution
Use SFINAE
// For all types except integral types:
template<typename T>
typename std::enable_if<!std::is_integral<T>::value>::type f(T t)
{
// ...
}
// For integral types only:
template<typename T>
typename std::enable_if<std::is_integral<T>::value>::type f(T t)
{
// ...
}
Note that you will have to include the full `std::enable_if` return value even for the declaration.
C++17 update:
// For all types except integral types:
template<typename T>
std::enable_if_t<!std::is_integral_v<T>> f(T t)
{
// ...
}
// For integral types only:
template<typename T>
std::enable_if_t<std::is_integral_v<T>> f(T t)
{
// ...
}
Problem
Suppose I have a template function: ``` template<typename T> void f(T t) { ... } ``` and I want to write a specialization for all primitive integer types. What is the best way to do this? What I mean is: ``` template<typename I where is_integral<I>::value is true> void f(I i) { ... } ``` and the compiler selects the second version for integer types, and the first version for everything else?