Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading std::to_string and std::to_chars for a custom type?

Tags:

c++

std

c++17

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))

like image 406
user1095108 Avatar asked Sep 14 '25 14:09

user1095108


1 Answers

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
}
like image 111
xskxzr Avatar answered Sep 17 '25 04:09

xskxzr