There was a discussion about function specialization here: Will specialization of function templates in std for program-defined types no longer be allowed in C++20?
In principal I understand, that it is better to overload instead of specialize. But how do you overload a std function template properly? The canonical answer seems to be: just overload in your custom namespace and then ADL kicks in. But this doesn't work, if fundamental types are involved. Non-working example:
#include <cmath>
namespace X {
class Y { };
Y sqrt(Y);
double foo(double x) { return sqrt(x); }
}
The example will only compile without the sqrt declaration for Y. One can solve the issue by overloading in namespace std instead:
#include <cmath>
namespace X {
class Y { };
}
namespace std { X::Y sqrt(X::Y); }
namespace X {
double foo(double x)
{
return sqrt(x);
}
}
This code does exactly what I want to do. However I am unsure, if this kind of overloading is permitted by the standard. At cppreference I don't find a hint toward this direction. And while this paper of Walter E. Brown proposes overloading as an alternative to specialization, I am unsure, if the above example uses it right (the paper doesn't give any examples).
std::sqrt(x);orusing std::sqrtinsidefoo?std::sqrt(x);see below. And writingusing std::sqrt(same for sin, exp aso.) all over the places in your code just to reactivate standard functions for fundamental types feels rather like a language flaw.#include <cmath>does not have to bringsqrtet al into global namespace. Your implementation does that for one reason or another, but that's not what the language guarantees. Normally you should be callingstd::sqrteverywhere, or sayingusing std::sqrt, regardless of whether you define your ownsqrt.std::sqrtto be something that it isnt. You want something else so you need to do a tiny bit extra. Its not a language flaw, i'd rather consider it as a langauge flaw ifstd::sqrtcould call whatever, but is not guaranteed to bestd::sqrt.