Allow DistanceFrom() to use user-defined abs() by default.

`std::abs()` doesn't work on custom types. While one can use the 3-argument version of `DistanceFrom()` to specify how to compute the distance, it's not as convenient as defining `abs()` for the custom type once in the type's namespace and then use the 2-argument version.

PiperOrigin-RevId: 735741409
Change-Id: If8fb668455eb963a2ccf089f7467c64965a2e7a6
This commit is contained in:
Zhanyong Wan
2025-03-11 06:58:43 -07:00
committed by Copybara-Service
parent 0bdccf4aa2
commit 4ee4b17bf5
3 changed files with 42 additions and 3 deletions
+4 -2
View File
@@ -3042,7 +3042,9 @@ auto Second(T& x, Rank1) -> decltype((x.second)) { // NOLINT
struct DefaultGetDistance {
template <typename T, typename U>
auto operator()(const T& lhs, const U& rhs) const {
return std::abs(lhs - rhs);
using std::abs;
// Allow finding abs() in the type's namespace via ADL.
return abs(lhs - rhs);
}
};
@@ -4470,7 +4472,7 @@ inline internal::FloatingEqMatcher<double> DoubleNear(double rhs,
//
// 1. compute the distance between the value and the target using
// get_distance(value, target) if get_distance is provided; otherwise compute
// the distance as std::abs(value - target).
// the distance as abs(value - target).
// 2. match the distance against the user-provided matcher m; if the match
// succeeds, the DistanceFrom() match succeeds.
//