Krzysztof Czainski wrote
2014-05-23 2:25 GMT+02:00 Vladimir Batov <
Vladimir.Batov@
>: [...]
template
boost::optional <TypeOut> operator()(TypeIn const&); //#3
surely seems attractive and with that interface converters can be easily used on their own (if needed/preferred) bypassing "convert" api altogether.
Let's take a simple case of, say, the "direction" class from the docs (which has no default constructor) and try converting it to std::string. Say, we want that conversion possible using a few converters with std::sstream-based being one of them. In that setting I say #1 has the following advantages (no matter how ugly I personally find it):
[...]
template<TypeIn, TypeOut>
boost::optional <TypeOut>
basic_stringstream_converter::operator()(const TypeIn& in) { boost::optional <TypeOut> out = boost::make_optional(boost:: convert_default_maker <TypeOut> ::make());
stream_.str(std::basic_string< char_type>()); stream_ << in; stream_ >> *out;
return out = stream_.fail() ? boost::optional <TypeOut> : out; }
template<TypeIn, TypeOut> boost::optional <TypeOut> lexical_cast_converter::operator()(const TypeIn& in) {
try { boost::optional <TypeOut> out_value = boost::make_optional(boost:: convert_default_maker <TypeOut> ::make()); *out_value = boost::lexical_cast <TypeOut> (in); return out; } catch (...) { return out = boost::optional <TypeOut> ; } }
Why would you make a default TypeOut to then assign to it, instead of:
template<TypeIn, TypeOut> boost::optional <TypeOut> lexical_cast_converter::operator()(const TypeIn& in) {
try { return boost::lexical_cast <TypeOut> (in); } catch (...) { return boost::none; } }
Indeed, typed in haste... embarrassing.
As for the
optional<TypeOut> operator()(TypeIn const&);
converter signature, then I am slowly warming up to it. If we declare
something like
namespace boost
{
template<class T> create_default() { return T();
}
outside "convert", then, say, lexical_cast might use it as well and get rid
of DefaultConstructibily requirement as well. And, indeed, as Alex pointed
out sometimes we'll be able to avoid using it altogether
template