0

What does the C++ standard have to say about overloading/implementing a templatized version of std::to_string like so:

#include <string>
#include <sstream>
#include <ostream>

namespace std {
  template<typename T>
  string to_string(const T& in)
  {
     ostringstream oss;
     oss << in;
     return oss.str();
  }
}

Is this expressedly disallowed? Or cause nasal-daemons to fly out of the nose?

g++ accepts the above code with --std=c++11 -Wextra -pedantic-errors, reports no errors, and the executable generates the output that I expect (which, of course, does not mean anything in context to my question)

7
  • unless an exception says otherwise you cannot add to std:: Commented Apr 25, 2024 at 12:57
  • why do you not do it the other way around. You can write your own function template, that calls std::to_string when possible and falls back to your implementation otherwise. There is no issue with that Commented Apr 25, 2024 at 12:58
  • 1
    "...It is undefined behavior to add declarations or definitions to namespace std or to any namespace nested within std, with a few exceptions noted below...." en.cppreference.com/w/cpp/language/extending_std Commented Apr 25, 2024 at 12:59
  • 3
    If you put your custom types in a namespace, then you can add a to_string function in that namespace that takes the specific classes as arguments. Then the compiler can use argument-dependent lookup to find the function if you just call it as to_string(object_of_namespace_class). Commented Apr 25, 2024 at 13:02
  • 1
    Proposed code is not only UB, but also will compete with already existing overloads of std::to_string. Commented Apr 25, 2024 at 13:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.