Suppose I have a function template and various overloads that "specialize" the template. As overloads are a better match than the template version during overload resolution, they will always get priorized.
template <typename T>
void dispatch(T&& t) {
std::cout << "generic
";
}
void dispatch(int) {
std::cout << "int
";
}
dispatch(5); // will print "int
"
dispatch(nullptr); // will print "generic
";
Now I have the case where I have a specialization that could work for a whole set of (unrelated) types, that however satisfy constraints from a concept, e.g.:
template <std::floating_point T>
void dispatch(T t) {
if constexpr(std::is_same_v<T, float>) std::cout << "float
";
else std::cout << "unknown
";
}
Unfortunately, this overload is on par with the generic case, so a call like dispatch(1.0f)
is ambiguous. Of course, I could solve this by providing explicit overloads for all types (that I currently know), but as the number of types in my real application is large (and more types of this concept may be added by clients) and the code for each of these types would be very similar (up to small differences that are known at compile-time), this would be a lot of repetition.
Is there a way to overload a function for a whole concept?
See Question&Answers more detail:os