|
Boost : |
From: Alexander Nasonov (alnsn_at_[hidden])
Date: 2006-04-04 15:13:55
I noticed that instantiated lexical_cast functions are parameterized
with array types. It's not optimal as array_to_pointer_decay is applied
to argument type immediately and original type is not user anywhere
else.
My idea is to define inlined lexical_cast that just transforms
the argument type and forward a call to detail::lexical_cast:
template<typename Target, typename Source>
inline Target lexical_cast(const Source &arg)
{
typedef typename detail::array_to_pointer_decay<Source>::type NewSource;
return detail::lexical_cast<Target,NewSource>(arg);
}
The detail::lexical_cast is almost an original lexical_cast except that
it doesn't transform the argument type. Additionally,
call_traits<>::value_type can be applied to the argument type:
namespace detail
{
template<typename Target, typename Source>
Target lexical_cast(
BOOST_DEDUCED_TYPENAME boost::call_traits<Source>::value_type arg)
{
detail::lexical_stream<Target, Source> interpreter;
Target result;
if(!(interpreter << arg && interpreter >> result))
throw_exception(bad_lexical_cast(typeid(Source), typeid(Target)));
return result;
}
}
I tested lexical_cast_test.cpp with gcc 3.4.4 [FreeBSD] 20050518.
Code was generated with bjam --v2 release.
Original size: 220316
Optimized: 201940 -17.95K ( 8.34% )
Optimized & call_traits: 197108 -22.66K ( 10.54% )
Additional transfomations can be applied. For example, enums can be
promoted to integral types. I'm a bit unsure about this, though.
This change could break enum types that have overloaded operator<<.
What is expected behavior in this case?
-- Alexander Nasonov
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk