// (connected)
Third, the type conversion related to the value and type
1, Lexical_cast
In program development, it is often necessary to convert the value of the digital object to a character text format, or an opposite operation. We can find such a function in the C / C standard library to perform conversion, such as Atoi. But they all have a common problem, complicated, lack of scalability, and more important is not safe enough.
You can simplify such an operation using lexical_cast.
Try {
INT i = 100;
String str = lexical_cast
Cout << "The string is:" << str << endl;
Str = "Error";
i = lexical_cast
}
Catch (Bad_Lexical_cast & Exobj) {
Cout << "NO, You can't Convert A /" Error / "To a int" << Endl;
Cout << exobj.what () << endl;
}
When "Error" is converted to int, this error will be discovered by Lexical_cast, then throws Boost :: Bad_lexical_cast this exception object.
There is also a requirement for the use of Lexical_castn:
1. The source type must be able to be output std :: ostream or std :: wostream object with operator << ()
2, the target type must be entered by the stream std :: istream or std :: Wostream object with operator >> ()
3, source type and target type must be copied
4. Target types must have Default Constructor
2, glimpse the interior
Template
Target Lexical_cast (Source Arg) {
Detail :: Lexical_Stream
Target Result;
IF (! ("(Interpreter << Arg && Interpreter >> Result)
Throw_exception (Bad_lexical_cast (TypeId (Target), TypeId (Source));
Return Result;
}
Among them, Lexical_Stream <> has a series of packages, mainly providing Operator << (Source) and Operator >> (TARGET) operation, the return type of these two operations is BOOL, which is used to determine if the operation is successful.
TARGET Result; for returning, this shows the reason why the target type must have a default constructor.
Interpreter << Arg and Interpreter >> Result is putting the value of Arg into the string stream, putting the value in the string of the string to the Result.
If the operation fails, throw the Bad_lexical_cast object. Where the Bad_LEXical_cast object saves the address of the type_info object of the source type and target type, which is convenient for the query for the error type.
Return 0; // end
Reference Source: Boost Conversion Library Documents