The main reason is that they do not belong there. They actually have nothing to do with strings. Stop and think about it. User-defined types must follow the same rules as built-in types, so every time you define a new user type, you need to add a function to std::string . This is actually possible in C ++: if std::string had a member of the to function template, without a common implementation, you can add specialization for each type and call str.to<double>() or str.to<MyType>() But is it really what you want. This does not seem like a clean solution for me, anyone writing a new class to add the specialization std::string . Putting this kind of thing into a string class is his bastard, and in fact it is the opposite of what OO is trying to achieve.
If you insisted on pure OO, they would have to be members of double , int , etc. (the constructor, really. this is what Python does, for example.) C ++ does not insist on pure OO and does not allow the use of basic types like double and int for have members or special constructors. Thus, free functions are both an acceptable solution and a single pure solution is possible in the context of the language.
FWIW: Converting to / from a text view is always a delicate problem: if I do this in the target type, then I have introduced a dependency on various sources and absorption of text in the target type --- and they can change over time. If I do this type of source or receiver, I make them type dependent, even worse. The C ++ solution is to define a protocol (in std::streambuf ) where the user writes a new free function ( operator<< and operator>> ) to handle conversions and expects permission to overload the operator to find the right function. The advantage of the free solution function is that the transformations are not part of either type data (which, therefore, should not know about sources and sinks), or the type of source or receiver (which, therefore, should not know about user-defined data types ) This seems like the best solution for me. And functions like stod are just handy functions that make one particularly frequent use easier to write.
James kanze
source share