Version of lexical_cast that doesn't use exceptions 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&lt;typename T1, typename T2&gt;
T1 lexical_cast(T2 const&amp; value, T1 const&amp; defaultValue = T1{})
{
    T1 convertedValue;
    std::stringstream ss;
    if (!(ss &lt;&lt; value) || !(ss &gt;&gt; convertedValue))
    {
        return defaultValue;
    }

    return convertedValue;
}


Here is the code on Coliru where I've been testing.
Since you have an already working lexical cast. Why not just wrap that?

namespace MyStuff
{
    template&lt;typename T1, typename T2&gt;
    T1 lexical_cast(T2 const&amp; value, T1 const&amp; defaultValue = T1{})
    {
        try
        {
            return boost::lexical_cast&lt;T1,T2&gt;(value);
        }
        catch(...) // Ignore all exceptions and use default.
        {
            return defaultValue;
        }
    }
}


The reason I would not advocate writing your own is the actually complicity of all the edge cases. Though your code embodies what is happening the actual code has not reflected this in a long time (you have basically written the deprecated version of boost::lexical cast).

Also the boost version has a whole bunch of special case optimizations.