HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Version of lexical_cast that doesn't use exceptions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lexical_castexceptionsversiondoesnthatuse

Problem

I love boost::lexical_cast but its usage of exceptions there is not preferred in most situations I use it.

I have implemented a version and it seems to work but I want to share it here to hopefully find any defects and/or simply find improvements.

template
T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
{
    T1 convertedValue;
    std::stringstream ss;
    if (!(ss > convertedValue))
    {
        return defaultValue;
    }

    return convertedValue;
}


Here is the code on Coliru where I've been testing.

Solution

I know I am quite late, but try_lexical_convert() can be utilized:

using boost::conversion::try_lexical_convert;
if(try_lexical_convert(source, target)) {
   // ...
}

Code Snippets

using boost::conversion::try_lexical_convert;
if(try_lexical_convert(source, target)) {
   // ...
}

Context

StackExchange Code Review Q#79682, answer score: 2

Revisions (0)

No revisions yet.