Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Synopsis

lexical_cast
bad_lexical_cast

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);
}

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. Source types that require wide-character streaming are wchar_t, wchar_t *, and std::wstring. Target types that require wide-character streaming are wchar_t and std::wstring.

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.

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

Exception used to indicate runtime lexical_cast failure.


PrevUpHomeNext