#include <x/value_string.H> #include <x/locale.H> x::locale l; std::string s; short n; // ... s=x::value_string<short>::to_string(n, l); // ... n=x::value_string<short>::from_string(s.begin(), s.end(), l);
The
x::value_string
defines the following functions:
to_string
(value, locale)
to_string
()
takes the instance of the template class parameter and converts
it to a std::string
using the locale given
by the second parameter.
from_string
(string, locale)
from_string
()
is the opposite, taking a string parameter, and converting it
to the value specified by the template class parameter.
For all natural integer and floating types,
x::value_string
uses standard library functions
to effect the conversion.
The template parameter may also be a std::string
,
which results in a from_string
() and
to_string
() that are effectively no-ops.
x::value_string
with custom classes
The x::value_string
template class works with
x::hms
and
x::ymd::interval
,
x::uriimpl
, and
x::uuid
classes.
To implement x::value_string
for any class,
define several member templates, as described below.
This is done for the purpose of converting an object into
some human readable form.
Object serialization template API
would be more appropriate for saving and storing objects where
readability is not a concern.
// ... class Widget { public: template<typename OutputIterator> OutputIterator to_string(OutputIterator iter, const x::const_locale &localeRef) const { // return iter; } template<typename InputIterator> static Widget from_string(InputIterator beg_iter, InputIterator end_iter, const const_locale &localeArg) { Widget w; // return w; } }; // ... Widget wInstance; x::locale l; std::string s=x::value_string<Winder>::to_string(wInstance, l);
The to_string
() template methods takes an output
iterator and a locale object
(which they may ignore, if it's irrelevant for this class), writes the
string representation of the object into the output iterator, and
returns the new iterator value.
from_string
()
must be a static method that takes
a pair of iterators. The pair
specifies the beginning and the end of a character or a character
sequence. The third argument is a
locale object.
from_string
() converts the character
sequence to a new object instance, and return it.
from_string
()
should throw an exception it can't parse the string.
Furthermore, the beginning and ending iterator sequence should define
the complete parsable sequence, and an exception should get thrown
if the object gets converted without consuming the entire input
sequence (however, the methods can allow this, if they want to).
#include <x/to_string.H> x::locale l; class Widget; // ... Widget w; // ... std::string s=x::to_string(w, l);
x::to_string
() invokes
x::value_string<class>::to_string
().