Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is specialization of std::to_string for custom types allowed by the C++ standard?

In C++11 and later, is it allowed to specialize std::to_string in the std namespace for custom types?

namespace std { string to_string(::MyClass const & c) { return c.toString(); } } 

Sample use-case:

int main() {     MyClass c;     std::cout << std::to_string(c) << std::endl; } 
like image 542
jotik Avatar asked Apr 10 '16 17:04

jotik


1 Answers

In C++11 and later, is it allowed to specialize std::to_string in the std namespace for custom types?

No. First of all, it is not a template function so you can't specialize it at all.

If you're asking about adding your own overload functions the answer still remains the same.

Documentation snippet from Extending the namespace std:

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

It is allowed to add template specializations for any standard library template to the namespace std only if the declaration depends on a user-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited.


In practice everything will probably work just fine but strictly speaking the standard says there is no guarantee of what will happen.


Edit: I don't have access to the official standard so the following is from the free working draft (N4296):

17.6.4.2 Namespace use

17.6.4.2.1 Namespace std

  1. The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.181
  2. The behavior of a C++ program is undefined if it declares

    2.1 — an explicit specialization of any member function of a standard library class template, or

    2.2 — an explicit specialization of any member function template of a standard library class or class template, or

    2.3 — an explicit or partial specialization of any member class template of a standard library class or class template.

    A program may explicitly instantiate a template defined in the standard library only if the declaration depends on the name of a user-defined type and the instantiation meets the standard library requirements for the original template.

  3. A translation unit shall not declare namespace std to be an inline namespace (7.3.1).
like image 150
James Adkison Avatar answered Sep 24 '22 02:09

James Adkison