Boost logo

Boost :

From: Preston A. Elder (prez_at_[hidden])
Date: 2005-01-26 23:07:47


Hi,

check out this code:

#include <boost/lexical_cast.hpp>
#include <iostream>

struct my_type
{
    int a;
    int b;
};

template<typename C, typename T>
std::basic_istream<C,T> &operator>>(std::basic_istream<C,T> &is,
                                    my_type &mt)
{
    is >> mt.a >> mt.b;
    return is;
}

int main()
{
    std::string input = "1 2";
    my_type mt;
    try
    {
        mt = boost::lexical_cast<my_type>(s);
        std::cout << "TEST 1: " << mt.a << " " << mt.b << std::endl;
    }
    catch (boost::bad_lexical_cast &)
    {
        std::cout << "TEST 1 FAILED" << std::endl;
    }

    input = "3 4";
    std::stringstream ss;

    ss << s;
    ss >> mt >> std::ws;
    if (ss.eof())
        std::cout << "TEST 2: " << mt.a << " " << mt.b << std::endl;
    else
        std::cout << "TEST 1 FAILED" << std::endl;

    return 0;
}

The output I get is:
TEST 1 FAILED
TEST 2: 3 4

My investigation has shown that this occurs because boost::lexical_cast
calls stream.unsetf(std::ios::skipws);

My question is, why does it do this - as this specifically stops
lexical_cast from working with complex types. So could this be an option,
or completely disabled, or made an option (somehow) to lexical_cast?

I understand some logic to not skipping whitespace, however I believe its
use is limited - especially since there is a specialization for
std::string and std::wstring already which does not even use operator>>.

As a side note, yes, I could change my operator>>, however the sample
operator>> above is typical for an operator>> for a complex class, almost
always they assume that skipws is turned on, and don't bother checking.

-- 
PreZ :)
Founder. The Neuromancy Society (http://www.neuromancy.net)

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk