Boost C + + formatted output function library: Format

Source: Internet
Author: User
Tags posix sprintf

His greatest feature is that it can use printf's formatted string in C to produce output for C + + iostream, or to generate formatted strings, compared to C + + iostream's Manipulator,boost::format, which is more intuitive to use, Simple. And unlike printf, he has the C + + iostream type safe, which can support custom types of output

The official website of the introduction can refer to: http://www.boost.org/doc/libs/1_44_0/libs/format/index.html


One, C printf and C + + iostream

Generally in the C language, everyone should be very accustomed to use the printf function (reference) to do the output of the action. Because printf has a powerful, simple format output ability, so many people are considered to use C + +, will also discard the more secure iostream (reference), and continue to use printf, fprintf, sprintf such functions to do the format of string processing, output.

In practice, however, the C-language printf is not very safe to use. The main problem is that when you use printf, it's not the type safe! A very simple example of this is:

char * x = "ABCD";
printf ("%d\n", X);

Since you need to specify the type of the output variable (%d,%f, and so on) when using printf output, it is possible to accidentally mistake it and become the same as above, specifying the wrong output type. In addition, because of the problem of printf design, if you want to output a custom type, it will become relatively cumbersome, and if you want to use the sprintf function to produce a formatted string, it is more likely to create memory use problems.


Basically C + + 's iostream has solved these problems. If the use of C + + iostream, in fact, in all aspects of the problem is relatively small, and relatively simple to use; for the output of custom types, you can use the operator overloading method to write an output for each category that belongs to itself and conforms to the iostream usage method.


Second, the basic use of Boost::format

The format of boost, the library of functions, is basically designed to make it easier for users to use C + + 's iostream for formatted output! Boost::format provides a syntax definition for a format string similar to that of the printf C, which allows the user to easily format output with the same effect as printf, while maintaining the C + + Iostraem Of the advantages, for the C + + programmer to do the format output, Boost::format should be a quite useful, but also worth a try of the library!

Boost::format is a header-only function library, as long as the preparation of the header file, without pre-compilation can be used, in the use of considerable convenience. In this library, the main thing is to provide a format category (note one) to allow the programmer to do the operation. The following is a simple example:







}

First of all, to use Boost::format, we have to include"boost/format.hpp" this header file first.
and Boost::format closest to the use of printf, that is, the above form (posix-printf style) ~ Such a writing in the output through the cout after the result, will and

printf ("%2.3f,%d\n", 1.23456, 12);

Exactly the same.

In addition to the above "posix-printf style", there are also so-called "simple style" (simple style) usage can be used, the following is a simple example:

cout << Boost::format ("%1%,%2%")% 1.23456 << Endl;

In this style of writing, is in the format of the string, with "%1%" to represent the first variable, with the "%2%" to represent the second variable, through such a definition, we can adjust the order of the variables, but also can be repeated use of a certain variable ~ For example:

cout << Boost::format ("%1%,%2%,%1%")% 1.23456 << Endl;

In this case, the output will be "1.23456, 12, 1.23456". However, since this does not specifically specify formatted settings, all variables will be output in a preset way.

1. Operation of the Boost::format object

As mentioned earlier, Boost::format is actually a type that, when used, actually produces a type of Boost::format object for subsequent operations, and all variables are passed to this object sequentially through the call operator% (Note II) , and finally pass the output of his data to cout through operator<<.

In contrast to this, printf itself is a variable number of parameters (variable-length argument) function, so all the variables to be output, are separated by commas, in the form of function parameters passed in. So while these two look very similar in the way they are written, they are completely different in terms of concepts and practices.
As in the following example:

cout << Boost::format ("%1%,%2%")% 1.23456 << Endl;

Can actually be seen as:

cout << ((Boost::format ("%1%,%2%")% 1.23456) << Endl;

And because Boost::format actually works in the form of objects, the actual execution process is equivalent to:

Boost::format FMT ("%1%,%2%");
Fmt% 1.23456;
Fmt% 12;
cout << fmt << Endl;

This also means that the user can record the Boost::format object and use it repeatedly.

For example, here is an example of reusing Boost::format objects:

Boost::format fmt ("test:<%1.2f,%1.2f >");
cout << (fmt% 1.234% 123.1) << Endl;
cout << fmt% 5.678% 1 << endl;

It is important to note, however, that variables passed through operator% to the Boost::format object (FMT) are stored inside the objects, so the variables can be passed in batches, but if the number of variables does not match, there is no error in the compilation phase. However, the implementation phase will still cause the program to crash, so use must be careful. However, after you have output, you can re-pass in the new variable and reuse the same Boost::format object.

2. Generating strings through Boost::format

The method mentioned above is to output the result of Boost::format directly to the usage of ostream, if we want to use the result of formatted output as a string. Very simple, because boost has already provided the corresponding function can do this thing ~ basically there are two methods, the first method is to use BOOST::STR () This function:

string tmp = BOOST::STR (Boost::format ("<%1%>")% "hi!");

Another method is to use the BOOST::FORMAT::STR () function:

Boost::format FMT ("<%1%>");
Fmt% "hi!";
string tmp = FMT. STR ();

Or:

string tmp = (Boost::format ("<%1%>")% "hi!"). STR (  );  

The two are basically the same, just a different way of writing.

3. Syntax details

The previous two usages of the so-called POSIX printf style and simple style are probably mentioned. In fact, the syntax of the formatted string used by Boost::format is based on the Unix98 Open-group printf, and then some extensions are made; its form is:

%[N $][flags [width] [. precision] Type-char

Most of the content is the same as the traditional printf (reference), only partially. (Note IV)

Like in the Flags section, Boost::format except the original "-" is left-aligned, but also the new alignment of the "=", as well as the internal alignment (internal alignment) "_", which is not printf. In addition to the use of "%%" to output the "%" symbol, but also more can be used "% n t" to fill n spaces, or with "%| N T X | "To fill in the function of n x (x is a single character).

In practice, it should be broadly divided into the following forms:

% n: (simple style) The simplest, unformatted, simplified notation, where N is only a simple token is the first of several variables.
% Spec: (posix-printf style format string) This part is mainly compatible with the wording of printf, basically can be used in the wording of printf directly to use. Of course, the Spec section also has support for boost::format additional definitions of new things to use.
%| Spec | : This is with "|" To do a separate representation. Spec is basically the same as the former, the main advantage of this writing is that you can omit the specified type of characters ("type-conversion character" in printf), but also enhance the readability of the code.

Example: "%|-5 | "is to represent the left alignment, width is 5, according to the variable type of different, and"%-5g","%-5f", etc. are equivalent.

Which, it seems, a more special wording, perhaps "%|1$+4.2| The meaning of this form is basically to put the first variable (1$) in the form of a "+4.2", and there is no particular type specified for the output, so the behavior during the execution phase may vary depending on the type of the variable passed in.



4. Example

The following example illustrates the simple way boost::format works

Mode one cout << boost::format ("%s")% "output content" << endl;//mode two std::string s;s = str (Boost::format ("%s")% "output") ; cout << s << endl;//mode three Boost::format formater ("%s"); formater% "Output content"; std::string s = formater.str (); cout &L t;< s << endl;//mode four cout << boost::format ("%1%")% Boost::io::group (hex, showbase, +) << Endl;


Iii. Effectiveness Issues

Although the use of Boost::format is full of convenience, but in fact, the effectiveness of the surface, is not very good, this is in the official website has been specifically proposed. Basically, in general, the performance of printf will be the best, iostream will be slower than printf, and Boost::format will be slower because there are other overhead. The official also provides some test data, if in release mode, the time required for the iostream operation will be 1.6 times times of printf, while the Boost::format time will be iostream 2 ~ 3 times times, that is, about printf of 3 ~ 5 times times.


From this test data should be able to find, in fact, boost::format performance is not good. So if the program itself's performance bottleneck is in this kind of string output, processing, then using Boost::format may not be a good choice, because he does have the potential to make performance worse, so in this case, the best way to go back to using printf ~

However, in fact, the general program of the main performance bottleneck should not be in this part, so in this situation, the use of Boost::format should not have a significant impact on overall performance, relatively, it is possible to use Boost::format to reduce the time cost of many development. So if it is in this situation, Boost::format should still be quite practical.

Iv. Conclusion

For the introduction of Boost::format, it is probably the first to tell a paragraph. In fact, the talk should not be very complete, there are many details have been heresy skipped, just a simple introduction. Really want to fully learn the words, may still have to go back to the official website to see, believe that if willing to take the time, should be able to dig more advanced usage!


Notes

The implementation is a template class:basic_format.
Boost::format's operator% definition method is very similar to Ostream's operator<<, which is in the form "format& format:: operator% (const t& x)", will return a format reference, so you can always use operator% string down.
For the user to customize the type, as long as there is a definition operator<<, so that he can be output through the iostream, it can be used on the Boost::foramt.
Visual C + + printf does not seem to support the "n $" (positional format specification) of the formatted string, but it should be available on GCC.

Boost C + + formatted output function library: Format

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.