1

I have a large project where namespace std is extended with std::abs for a custom type like in the following example.

struct A {
    int a;
};

namespace std {
    template <int i>
    auto abs(A<i> const& x) -> A<i>
    {
        return A<i>(std::abs(x.a));
    }
}

From my understanding, this is undefined behaviour, as it is not a template specialisation for std::abs, so I would like to refactor this. Is there any way to reasonably do this? The call std::abs(A<i>) is often used.

Henk
  • 826
  • 3
  • 14
  • 4
    A common way is not to call `std::abs` directly, but to use `using std::abs;` and then just call `abs`. This will find you custom `abs` even when it is not in `std`. Note that, since C++20, IIRC, you even cannot add specializations of function templates into `std`. This question is relevant: https://stackoverflow.com/q/6380862/580083. It is the same problem more commonly solved for `swap` function. – Daniel Langr Dec 21 '21 at 12:54
  • @DanielLangr You recall correctly: https://stackoverflow.com/questions/52760580/will-specialization-of-function-templates-in-std-for-program-defined-types-no-lo – NathanOliver Dec 21 '21 at 13:05
  • So this would have to be changed at the call site? – Henk Dec 21 '21 at 13:05
  • 2
    Yes, all of your call sites are bad as this `abs` should not be in `std`. Add it to the same namespace that `A` is defined in and then change the call sites to just use `abs` or `your_ns::abs` – NathanOliver Dec 21 '21 at 13:06

0 Answers0