Boost logo

Boost :

From: shams (shams_at_[hidden])
Date: 2006-08-06 21:32:47


Sorry, never got a reply in the users list,

So fwd'ed here...

-------- Original Message --------
Subject: lexical_cast problem
Date: Fri, 4 Aug 2006 16:53:10 +1200
From: shams <shams_at_[hidden]>
To: boost-users_at_[hidden]

Hi,

Here is a sample custom string class that I am tring to get working with
lexical_cast but it gives me compile errors. Can you please see what I am doing
wrong here. More explanation below.

OTOH if I use a custom lexical_cast using wstringstream it works fine.

// main.cpp
#include <string>
#include <iostream>

#include "boost_1_33_1/boost/lexical_cast.hpp"

using namespace std;

class String : public wstring
{
public:
        String()
        {
        }

        String(const wchar_t *str) : wstring(str)
        {
        }

        String& operator=(const String& Rhs)
        {
                return static_cast<String&>(wstring::operator=(Rhs));
        }
};

// This is commented cause lexical_cast wants bool return value.
#if 0
template<class OutputStream>
OutputStream& operator<<(OutputStream &o, const String &s)
{
        return o << s.c_str();
}
#endif

template<class OutputStream>
bool operator<<(OutputStream &o, const String &s)
{
        o << s.c_str();

        return true;
}

// This is commented cause lexical_cast wants bool return value.
#if 0
template<class InputStream>
InputStream& operator>>(InputStream &i, String &s)
{
        wstring ws;

        i >> ws;

        s.assign(ws);

        return i;
}
#endif

template<class InputStream>
bool operator>>(InputStream &i, String &s)
{
        wstring ws;

        i >> ws;

        s.assign(ws);

        return true;
}

int main()
{
        // This line causes errors both on MSVC and GCC.
        wcout << boost::lexical_cast<String>(10);

        // These lines DONT cause errors and work ok.
        String s = L"hello";

        wcout << s;
        wcout << endl;

        wcin >> s;
        wcout << s;
        wcout << endl;

        return 0;
}


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