Boost logo

Boost Users :

From: John F Meinel Jr (boost_at_[hidden])
Date: 2004-03-15 22:41:04


I found that when I call boost::lexical_cast<std::string>() with an
object that has virtual functions, it fails to dereference the virtual
functions. It also cannot use an Abstract base type. Attached is example
code.

I think the problem is simply that the file boost/lexical_cast.hpp, on
line 185 has:
     Target lexical_cast(Source arg)
This should be
     Target lexical_cast(Source& arg)

At least, this fixes all of my problems.
John
=:->


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

struct A { virtual int f() const = 0; };

struct B : A { virtual int f() const { return 1; } };

struct C : B { virtual int f() const { return 2; } };

std::ostream& operator<<(std::ostream& os, const A& a) {
  return os << a.f();
}

int main()
{
  C c; std::string s;
  std::cout << c << std::endl; //This should print 2
  s = boost::lexical_cast<std::string>(c);
  std::cout << s << std::endl; //This should print 2
  s = boost::lexical_cast<std::string, B>(c);
  std::cout << s << std::endl; //This returns 1, not 2
  //This fails because it tries to instantiate an object of type A. Why???
  s = boost::lexical_cast<std::string, A>(c);
  std::cout << s << std::endl;
}


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