3

I have an arithmetic custom type with a to_string() member. I'm thinking about overloading std::to_string in the std namespace for the type, but would this count as namespace pollution?

EDIT: I'm thinking about this, so that this expression SFINAE would work for the type: -> decltype(std::to_string(std::declval<T>()), void(0))

xskxzr
  • 12,442
  • 12
  • 37
  • 77
user1095108
  • 14,119
  • 9
  • 58
  • 116
  • 1
    [This extending the `std` namespace reference](https://en.cppreference.com/w/cpp/language/extending_std) could be useful. In short, overloading e.g. `std::to_string` is not allowed (and leads to UB). – Some programmer dude Jul 07 '18 at 06:21
  • 1
    An alternative could be to keep `to_string` and `to_chars` in your own namespace, and than [leverage argument dependent lookup](https://stackoverflow.com/q/4782692/2486888). But it may be tricky. –  Jul 07 '18 at 06:28
  • Could we see your full proposal? (interested) – Paul Sanders Jul 07 '18 at 06:52
  • I'll just experiment with ADL, hopefully it will work. – user1095108 Jul 07 '18 at 06:58

1 Answers1

3

As Some programmer dude pointed out in the comment, you cannot add declarations into std namespace in this case.

Like this post, a workaround is to write your to_string in the same namespace as your custom class, and use using std::to_string to bring std::to_string in overload resolution when you want to use to_string for generic type. The following is an example:

#include <string>

struct A {};

std::string to_string(A) {return "";}

namespace detail { // does not expose "using std::to_string"
    using std::to_string;
    template <typename T>
    decltype(to_string(std::declval<T>()), void(0)) foo() {}
}
using detail::foo;

int main()
{
    foo<int>();      // ok
    foo<A>();        // ok
    // to_string(0); // error, std::to_string is not exposed
}
xskxzr
  • 12,442
  • 12
  • 37
  • 77