Boost logo

Boost Users :

From: François Duranleau (duranlef_at_[hidden])
Date: 2006-03-15 18:03:50


Hi!

If I read the documentation correctly about boost::lexical_cast, for a
convertion between two types to work, the source type must be
OutputStreamable and the target type must be InputStreamable (plus some
other requirements about copying and default construction).

Then, any idea why the following code does not work?

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

using namespace std ;

struct vec
{
     enum static_size_type { size = 2 } ;
     double data[ size ] ;

     vec()
     {
         for ( int i = 0 ; i < size ; ++ i ) data[ i ] = 0.0 ;
     }
} ;

istream& operator >> ( istream& in , vec& v )
{
     for ( int i = 0 ; i < vec::size ; ++ i ) in >> v.data[ i ] ;
     return in ;
}

ostream& operator << ( ostream& out , const vec& v )
{
     out << v.data[ 0 ] ;
     for ( int i = 1 ; i < vec::size ; ++ i ) out << ' ' << v.data[ i ] ;
     return out ;
}

int main()
{
     string arg = "1 2" ;
     try
     {
         vec v2 = boost::lexical_cast< vec >( arg ) ;
         cerr << "lexical_cast: " << v2 << endl ;
     }
     catch ( const boost::bad_lexical_cast& e )
     {
         cerr << e.what() << endl ;
     }
     return 0 ;
}
/////////////////////////////////////////////////////////////////////////

I use g++ 4.0.2 and Boost 1.33.1. The program compiles, but when executed,
I get a boost::bad_lexical_cast exception. However, if I change vec::size
to 1 and the variable arg in the main function to "1", then everything
runs fine. Any other values greater than 1 won't work (with an appropriate
source string, of course).

There is an example a little more detailed here:
http://www-etud.iro.umontreal.ca/~duranlef/code/lexical_cast_problem.cpp

In that example, I manually output the string to a stringstream and then
input a vec from the stream, check that I at the end of the stream, and
everything runs ok, but not with the lexical cast. I guess I must be doing
something stupid somewhere, but I don't see it.

Thanks for any help,

-- 
François Duranleau
LIGUM, Université de Montréal
"Conflict may erupt at any time and any place. War is the destiny of which
  humanity can never wash its hands."
                          - Emperor Dornkirk, in _The Vision of Escaflowne_

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net