Is it good practice to overload math functions in the std namespace in C ++

I am writing a C ++ class that represents an arithmetic type (C ++ wrapper around mpfr ), and I would like to support some of the functions found in <cmath> (Take std :: sqrt as an example).

So, I have the following class:

namespace ns
{
  class MyClass
  {
      /* ... */
      public:
      friend MyClass sqrt(const MyClass& mc);
  };
}

And I can use it as follows:

MyClass c;
/* ... */
MyClass d = ns::sqrt(c);
MyClass e = sqrt(c); // Apparently I don't have to specify ns::

But I can not use it like this:

MyClass f = std::sqrt(c);

Compiler (g ++ (Debian 4.7.2-5)): "there is no corresponding function to call sqrt (ns :: MyClass &)".

This is normal, but for me it is a problem. I need this to be valid, because MyClass is supposed to be used in existing template functions (which I should not modify). For instance:

template <typename T>
void func(T a)
{
    /* ... */
    T c = std::sqrt(a);
    /* ... */
}
int main()
{
    func<float>(3);
    func<MyClass>(MyClass(3));
    /* ... */
}

The following code snippet really solves my problem:

namespace std
{
  using ns::sqrt;
}

std . , .

? , ?

?

+4
4

, (§17.6.4.2.1):

++ undefined, std std, . std , , .

, . ( - ).

- .

+5

std . swap ( std, ): , . sqrt,

using std::sqrt;
a=sqrt(b);

, "" std::sqrt ( " " using), - Koenig lookup (, , , // Apparently I don't have to specify ns::).

+5

, , :

template <typename T>
void func(T a)
{
    using std::sqrt;

    /* ... */
    T c = sqrt(a);
    /* ... */
}

std- ( ).

+1
source

It is not a good idea to put it in the std namespace.

Since you have your own namespace, you can import sqrt into your namespace and add specialized functions sqrt:

namespace ns {
  using std::sqrt;
  MyClass sqrt(const MyClass &)
}

ns::sqrt(...);
+1
source

Source: https://habr.com/ru/post/1533820/


All Articles