Opened 11 years ago

Closed 11 years ago

#5783 closed Bugs (fixed)

lexical_cast fails for types whose operator<</>> are templated on stream type

Reported by: gredner@… Owned by: Antony Polukhin
Milestone: Boost 1.48.0 Component: lexical_cast
Version: Boost Development Trunk Severity: Regression
Keywords: Cc:

Description

The following code does not compile:

#include <boost/lexical_cast.hpp>

#include <iostream>
#include <string>

struct Foo
{
  Foo() : f(2) {}
  int f;
};

template <typename OStream>
OStream& operator<<(OStream& ostr, const Foo& foo)
{
  ostr << foo.f;
  return ostr;
}

int main()
{
  Foo foo;

  // OK!
  std::cout << foo << std::endl;

  // Does not compile!
  std::cout << boost::lexical_cast<std::string>(foo) << std::endl;
}

The problem is that inside lexical_cast there is a stream-like type called lexical_stream_limited_src which has a bunch of operator<< overloads which all return bool, and the rest of the implementation relies on these being called, and treats "x << y" expressions as returning bool. However, in the example above, such expressions match the template operator<< instead.

I ran into this because boost::fusion uses operator<<s of this type. So, while it is possible to stream a fusion::pair to an ostream, it is not possible to lexical_cast it to string.

One solution would be to get rid of the bool return type for lexical_stream_limited_src::operator<<, and instead for these methods to save in a boolean member variable whether the call succeeded or failed, and for client code of this class to check the member after the call.

Change History (3)

comment:1 by Antony Polukhin, 11 years ago

Milestone: To Be DeterminedBoost 1.48.0
Owner: changed from nasonov to Antony Polukhin
Severity: ProblemRegression
Status: newassigned

comment:2 by Antony Polukhin, 11 years ago

Great thanks for reporting this bug!

comment:3 by Antony Polukhin, 11 years ago

Resolution: fixed
Status: assignedclosed

(In [73818]) Fixes #5783

Fixes ambiguities with operators >> and <<. Adds tests for such cases.

Note: See TracTickets for help on using tickets.