In C++, Java, C# and Kotlin, multiple implementations of a method are allowed, with differing numbers and types of arguments. The compiler uses the number of arguments and their types to determine which overload was intended. Function and operator overloading has a key limitation: polymorphic functions can't restrict their type arguments to types for which a given overload exists.
maybe true for Java, C#, and Kotlin, but in C++ you can restrict your type arguments to require a specific overload:
#include <utility>
void overloaded(int) {}
void overloaded(char*) {}
template<class T> void other()
requires requires { overloaded(std::declval<T>()); } {}
int main() {
other<int>(); // compiles
other<char*>(); // compiles
// other<int*>(); // does not
}
and even before constraints you’d probably never do this:
Instead, this second method must itself be overloaded for each type that has an overload of the original method, resulting in many boilerplate definitions instead of a single polymorphic definition.
you’d just use a template function and let it fail somewhere in instantiation.
C++-style ad-hoc polymorphism has other problems, but these particular ones I think are not relevant.
maybe true for Java, C#, and Kotlin, but in C++ you can restrict your type arguments to require a specific overload:
and even before constraints you’d probably never do this:
you’d just use a template function and let it fail somewhere in instantiation.
C++-style ad-hoc polymorphism has other problems, but these particular ones I think are not relevant.