| Home | Libraries | People | FAQ | More

## Synopsis

Library features defined in boost/lexical_cast.hpp:

    namespace boost
    {
        class bad_lexical_cast;
        template<typename Target, typename Source>
          Target lexical_cast(const Source& arg);
    }

### lexical_cast

    template<typename Target, typename Source>
      Target lexical_cast(const Source& arg);

Returns the result of streaming arg into a standard library string-based stream and then out as a Target object. Where Target is either `std::string` or `std::wstring`, stream extraction takes the whole content of the string, including spaces, rather than relying on the default `operator>>` behavior. If the conversion is unsuccessful, a `bad_lexical_cast` exception is thrown.

The requirements on the argument and result types are:

- Source is OutputStreamable, meaning that an `operator<<` is defined that takes a `std::ostream` or `std::wostream` object on the left hand side and an instance of the argument type on the right.
- Target is InputStreamable, meaning that an `operator>>` is defined that takes a `std::istream` or `std::wistream` object on the left hand side and an instance of the result type on the right.
- Target is CopyConstructible [20.1.3].
- Target is DefaultConstructible, meaning that it is possible to default-initialize an object of that type [8.5, 20.1.4].

The character type of the underlying stream is assumed to be `char` unless either the `Source` or the `Target` requires wide-character streaming, in which case the underlying stream uses `wchar_t`, `char16_t` or `char32_t`. Wide-character streaming is currently detected for:

- Single character: `wchar_t`, `char16_t`, `char32_t`
- Arrays of characters: `wchar_t *`, `char16_t *`, `char32_t *`, `const wchar_t *`, `const char16_t *`, `const char32_t *`
- Strings: `std::basic_string`, `boost::containers::basic_string`
- `boost::iterator_range<WideCharPtr>`, where `WideCharPtr` is a pointer to wide-character or pointer to const wide-character

| Important

Many compilers and runtime libraries fail to make conversions using new Unicode characters. Make shure that the following code compiles and outputs nonzero values, before using new types:

    std::cout
        << booat::lexical_cast<std::u32string>(1.0).size()
        << "  "
        << booat::lexical_cast<std::u16string>(1.0).size();

Where a higher degree of control is required over conversions, `std::stringstream` and `std::wstringstream` offer a more appropriate path. Where non-stream-based conversions are required, `lexical_cast` is the wrong tool for the job and is not special-cased for such scenarios.

### bad_lexical_cast

    class bad_lexical_cast : public std::bad_cast
    {
    public:
        ... // same member function interface as std::exception
    };

Exception used to indicate runtime lexical_cast failure.