boostorg / lexical_cast

General literal text conversions, such as an int represented as a string, or vice versa
https://boost.org/libs/lexical_cast
34 stars 58 forks source link

`lexical_cast` doesn't recognize `std::string_view` or `boost::string_view` #30

Closed pdimov closed 8 months ago

pdimov commented 4 years ago

As per title; lexical_cast has specializations for string types, but not for string view types. Reported on the C++ Slack.

sehe commented 2 years ago

Is this still current? I have just used boost::convert::try_lexical_convert just fine with both std::string_view and boost::iterator_range<>, so it would seem this has been fixed somewhere before 1.78.0?

pdimov commented 2 years ago

I think that it's still current, yes. Looking at https://godbolt.org/z/WMa7vhnT9, the function f1 that uses a string

int f1()
{
    std::string s1( "5" );
    return boost::lexical_cast<int>( s1 );
}

goes directly to boost::detail::lcast_ret_unsigned<std::char_traits<char>, unsigned int, char>::convert(), whereas the two functions using string views

int f2()
{
    std::string_view s1( "5" );
    return boost::lexical_cast<int>( s1 );
}

int f3()
{
    boost::string_view s1( "5" );
    return boost::lexical_cast<int>( s1 );
}

take the generic path using a stream.

Similarly, in https://godbolt.org/z/9W6M1c35e, f1

std::string f1()
{
    std::string s1( "5" );
    return boost::lexical_cast<std::string>( s1 );
}

does a straight string copy, whereas f2 and f3

std::string f2()
{
    std::string_view s1( "5" );
    return boost::lexical_cast<std::string>( s1 );
}

std::string f3()
{
    boost::string_view s1( "5" );
    return boost::lexical_cast<std::string>( s1 );
}

go through the slow stream path.

sehe commented 2 years ago

Ah. I completely misunderstood the problem description then. It's not that the conversions aren't supported, it's that they don't generate optimal code. The negative examples might actually be good addition for the original description.

pdimov commented 2 years ago

Edited to supply the code examples in case the CE links disappear.

apolukhin commented 8 months ago

Merged to master branch.

Many thanks for the bug report!