[ create a new paste ] login | about

Link: http://codepad.org/hn6MjKjm    [ raw code | fork ]

lexicalunit - C++, pasted on Feb 4:
#include <iostream>
#include <limits>

#include "lexical_cast.hpp" // hacked version

using namespace std;
using namespace boost;

struct foo
{
    public:
        foo(int i) : i(i) { }
        operator int() const { return i; };
    
    private:
        friend istream& operator>>(istream& is, foo& f);
    
        foo(); // no default ctor
        int i;
};

istream& operator>>(istream& is, foo& f)
{
   is >> f.i;
   return is;
}

int main()
{
    int invalid_as_uint = -1;
    int valid_as_uint = 5;
    unsigned default_uint = 6;

    // Normal form, throws.
    try
    {
        unsigned i = lexical_cast<unsigned> (invalid_as_uint);
        cout << i << endl;
    }
    catch (const bad_lexical_cast&)
    {
        cout << "bad lexical cast error" << endl;
    }

    // Overload for lexical_cast<optional<T>>, does not throw.
    optional<unsigned> i = lexical_cast<optional<unsigned> > (invalid_as_uint);
    if (i) cout << *i << endl;
    else cout << "invalid return value" << endl;
    
    i = lexical_cast<optional<unsigned> > (valid_as_uint);
    if (i) cout << *i << endl;
    else cout << "invalid return value" << endl;

    // Fallback form, does not throw, does not require Target be default-constructable.
    // Note the fallback form does not require an explicit template paramenter, which breaks with
    // the intention to model lexical_cast() after the standard _cast() functions.
    char invalid_foo = 5;
    foo default_foo (10);
    foo f = lexical_cast (invalid_foo, default_foo);
    cout << f << endl;

    // This is silly, but we can use optional types with the fallback form if we wanted...
    // Of course, there's no reason to use an optional type with the fallback form because
    // lexical_cast() would always return some valid value (assuming the given default is valid).
    optional<unsigned> ou = lexical_cast (invalid_as_uint, optional<unsigned> (default_uint));
    cout << *ou << endl;

    return 0;
}


Create a new paste based on this one


Comments: