Given a function such as:
template< typename T >
void function1( const T &t )
{
function2( boost::lexical_cast<std::string>(t) );
}
What kind of overhead is incurred if the type passed to function1
is already a std::string
?
Does the overhead vary, depending on the type I'm lexical_cast
-ing to?
Is it superfluous to make an overloaded function to bypass the cast? E.g.:
void function1( const std::string &t )
{
function2( t );
}
template< typename T >
void function1( const T &t )
{
function1( boost::lexical_cast<std::string>(t) );
}
The version of boost may be relevent to your answer, as I understand that lexical_cast
has received a few optimizations across revisions.
Since the documentation doesn't offer anything on this topic, I dug into the lexical_cast
source (1.51.0) and found that it does some compile-time checking on the types and decides a specific "caster class" that does the conversion. In case source and target are the same, this "caster class" will simply return the input.
Pseudo-codified and simplified from source (boost/lexical_cast.hpp:2268
):
template <typename Target, typename Source>
Target lexical_cast(const Source &arg)
{
static if( is_character_type_to_character_type<Target, src> ||
is_char_array_to_stdstring<Target, src> ||
is_same_and_stdstring<Target, src> )
// ^-- optimization for std::string to std::string and similar stuff
{
return arg;
}
else
{
/* some complicated stuff */
}
}
I can't directly see any optimizations for other identity casts, though, and looking through the normally selected lexical_cast_do_cast
"caster class" is making my head hurt. :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With