C ++ boost-lexical_cast

Source: Internet
Author: User
Header boost/lexical_cast.hpp
  • Motivation
  • Example
  • Outline
  • lexical_cast
  • bad_lexical_cast
  • Portability
  • Future Direction

In many cases, we have to convert a value to a character, just as int represents a string, or conversely, a string is interpreted as an int. this is common when data needs to be converted between different types within or outside the program, such as Windows and configuration files.

Standard C and C ++ provide many clever conversion methods. However, they vary in terms of ease of use, scalability, and security.

For example, the standard C function family represented by atoi has many limitations.

  • Conversion from a string to an internal data type can only be performed in one way. When C-based library functions are converted in turn, either sprintf is inconvenient to use and security compromise is selected; or non-standard functions, such as ITOA, are used, leading to loss of portability.
  • The convertible types are limited to the built-in numeric types, that is, Int, long, and double.
  • There is no general form to extend the convertible type range. For example, convert the string type to the plural or rational number.

The standard c Functions Represented by strtol have the same restrictions, but provide better control over the conversion process. However, such control is usually not needed or used. The scanf function family provides more powerful control, while also seriously lacking security and ease of use.

The standard C ++ provides stringstream for conversion. It provides a lot of process control over the conversion and formatting of I/O and any types to strings. However, it is very clumsy to use stringstream for simple conversions (additional local variables are required and cannot be embedded in expressions) and obscure (a temporary object of stringstream needs to be created when used in an expression ). Facets provides a wide range of conceptual support and convenience for controlling text performance, but its associated high thresholds require very high intervention for simple conversions.

lexical_castThe template method provides a convenient and consistent form for conversion from any type to a string or the opposite. The simplification of this conversion brings convenience at the expression level. For conversions that require more intervention, such as the control ratio of precision and formattinglexical_castWe recommend that you use the conventional stringstream method. For the conversion from number to number,numeric_castPossiblelexical_castProvides a more reasonable conversion.



The following example converts a command line parameter into a numerical sequence

int main(int argc, char * argv[]){    using boost::lexical_cast;    using boost::bad_lexical_cast;    std::vector<short> args;    while(*++argv)    {        try        {            args.push_back(lexical_cast<short>(*argv));        }        catch(bad_lexical_cast &)        {            args.push_back(0);        }    }    ...}

The following example converts numeric data to string

void log_message(const std::string &);void log_errno(int yoko){    log_message("Error " + boost::lexical_cast<std::string>(yoko) + ": " + strerror(yoko));}

The features of the database are defined in"boost/lexical_cast.hpp"Medium:

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

The test case is defined in"lexical_cast_test.cpp"Medium.


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

ReturnargInboundstd::stringstreamThenTargetThe result of the object. The conversion is implemented by the currentlexical_contextParameterization. If the conversion failsbad_lexical_castAn exception is thrown. Otherwise, a target object is returned.

The requirements for parameters and result types are as follows:

  • SourceYesStream outputThat is, you must providestd::ostreamObject.operator<<Operator implementation.
  • SourceAndTargetRequiredCopyable constructed(Copy constructor is provided) [Statement 1.3].
  • TargetYesStream InputThat is, you must providestd::istreamThe right side of the object is the result type instance'soperator>>Operator implementation.
  • TargetYesDefault ConstructionThat is, it is possible to initialize an object of this type by default (the default constructor is provided) [8.5,].
  • TargetYesValue OptionsOf [23.1].


class bad_lexical_cast : public std::bad_cast{public:    virtual const char * what() const throw();};

An exception is used to indicate the runtimelexical_cast.



The code and test framework has been compiled and approved in Microsoft Visual C ++ 6.0, Borland C ++ 5.5, and GNU g ++ 2.91. Tests Under Microsoft Visual C ++ 6.0 and Borland C ++ 5.5 were successful. Except for the stream of G ++, any integer is interpreted as a valid bool type, not just0And1, And other tests passed without any problems. To support out-of-the-box G ++, unrecommended standard header files<strstream>Compare<sstream>Priority.


Future Direction
  • A mechanism is required to provide service quality control, such as formatting and abnormal behavior. In line with the simple (easy to publish) principle, the current version removes an earlier experimental version.
  • Wide characters and incompatiblestd::basic_stringThe problem must be solved urgently.
  • You must be able to executeDo-something-reasonableConvertedinterpret_cast. For examplestd::numeric_limits<>::is_specializedInnumeric_castAndlexical_castSelect the appropriate one.
Copyright Kevin Henney, 2000 Chinese Translation: lythm, 2002

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.