Opened 13 years ago

Closed 13 years ago

#4009 closed Bugs (fixed)

lexical_cast to multimember object fails

Reported by: Darko Veberic <darko.veberic@…> Owned by: nasonov
Milestone: Boost 1.43.0 Component: lexical_cast
Version: Boost 1.40.0 Severity: Not Applicable
Keywords: Cc: darko.veberic@…

Description

According to the documentation, the only relevant requirement for the lexical_cast<target>(source) is that the target is input-streamable. Having a simple class

struct Foo {
  int fA;
  int fB;
};

with input operator

istream&
operator>>(istream& is, Foo& f)
{
  return is >> f.fA >> f.fB;
}

should satisfy all the requirements. Nevertheless, the code

const string s = "137 13";
const Foo f = lexical_cast<Foo>(s);

compiles without any warnings (g++ 4.4.1) but eventually throws a bad_lexical_cast exception. Of course, using a non-optimized non-boost version of the lexical cast

template<typename T, typename U>
T
LexicalCast(const U& u)
{
  stringstream ss;
  ss << u;
  T t;
  if (ss >> t)
    return t;
  else
    throw bad_lexical_cast();
}

works fine for the class in the example above. Are there additional requirements on the target type that are not mentioned in the documentation or is this a really severe bug?

Change History (3)

comment:1 by Darko Veberic <darko.veberic@…>, 13 years ago

Cc: darko.veberic@… added

comment:2 by Steven Watanabe, 13 years ago

You need to use std::ws between the two integers, because Boost.LexicalCast turns off skipping white space by default.

comment:3 by Darko Veberic <darko.veberic@…>, 13 years ago

Resolution: fixed
Severity: ShowstopperNot Applicable
Status: newclosed

thanks, this solved the problem. the input operator thus has to be defined as

istream&
operator>>(istream& is, Foo& f)
{
  return is >> f.fA >> ws >> f.fB;
}

(what a n00b mistake...)

Note: See TracTickets for help on using tickets.