Yes, this is possible. One way of doing this is to use SFINAE:
template <class T, std::enable_if_t<std::is_integral_v<T>, int> = 0>
void fun(T b)
{
/// Code for integer type
}
template <class S, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
void fun(S a)
{
/// Code for floating type
}
Note that the 2 conditions for the enable_if
s have to be disjoint, which we can see from the documentation of std::is_integral
and std::is_floating_point
that they are. If they weren't, the conditions would have to look like std::is_integral_v<T> && !std::is_floating_point_v<T>
.
What is happening here is that the std::enable_if_t
makes one of the overloads "fail to compile" if the condition is not satisfied, which means that the overload is simply not considered due to SFINAE.
If you are using C++17, you might want to consider using if constexpr
instead:
template <class T>
void fun(T b)
{
if constexpr (std::is_integral_v<T>) {
/// Code for integer type
} else if constexpr (std::is_floating_point_v<T>) {
/// Code for floating type
}
}