Boost C ++ format the handler output function Syntax: Format

Source: Internet
Author: User
Tags format definition posix

Good article, original post: viml.nchc.org.tw/blog/paper_info.php? Class_id = 1 & sub_id = 1 & paper_id = 194

This article was previously reported
The first article in the boost C ++ libraries series. The introduced handler is used in boost to format the handler: boost: format.

Its biggest feature is that it can use the printf formatted string in the C ++ statement to extract the iostream of C ++ or generate formatted strings; similar to the manipulator of C ++ iostream, boost: format is more intuitive and easy to use. In addition, unlike printf, it has the type safe of C ++ iostream, which can support vertex locality distribution from others.

For details about the official website, refer to http://www.boost.org/doc/libs/41044_0/libs/format/index.html.

C printf and C ++ iostream

Generally, when speaking in C, you should use the printf function to perform the animated work. Because printf has the ability to format images in a large and simple manner, many users may use C ++ as a secure iostream ), zookeeper
The formats printf, fprintf, and sprintf are used to format and parse strings. (In other words, heresy does not fully remember how iostream should be formatted and exported ...)

But in practice, C producer's printf is not very secure in use. The main problem is that the type is not safe when printf is used! A very simple example is:

char*   x = "abcd";printf( "%d", x );

When printf is used for data export, you must specify the type (% d, % F, etc.) of the output data ), in fact, when you are not careful about it, you may be able to get the mirror. The imaging above is the same, and the out-of-the-box sequence of the mirror sequence is specified. In addition, it is also caused by the printf design issues. Therefore, if you want to extract custom types of data, it will become quite difficult.

If the sprintf function is used to generate formatted strings, it is more likely to generate problems in the use of the memory, heresy has previously written an article "replacing insecure sprintf with snprintf/asprintf", that is, in this part of things, interested people can take a test.

Basically, the iostream of C ++ has solved these problems. If the iostream of C ++ is used, in fact, there are a lot of problems in all aspects, and there are also a lot of problems in use; the operator overloading method can be used for outbound operations similar to external operations, it is assumed that each category has an output that corresponds to itself and conforms to the iostream usage method.

However, if you mention formatting the output part, although the iostream of C ++ provides a "Manipulator" to allow the user to control the output format ), but heresy itself is included, and heresy knows that there are people in the program c ++. It seems that most of them are still using the printf Series Function in zookeeper, instead of using the manipulator of iostream. In heresy
It seems that he is neither easy to remember nor use...

 

Boost: Format basic usage

The boost format function (officially introduced ), basically, it was developed to allow the program designer to use the iostream of C ++ to format and export it more simply! As heresy mentioned at the beginning, boost: format provides a format string equivalent to C's printf, to enable developers to achieve and
In the same way as printf, the image is formatted and exported. At the same time, he also keeps the various parameter values of iostraem in C ++, for C ++ developers who want to format and export code, boost: format should be a handy and well-worth-writing function!

Boost: format is a header-only function. You only need to configure the header before using the function. You do not need to configure the function first, which is convenient in usage. In this function, a format type is provided.(Region 1)To allow the program sender to perform operations. The following is a simple example:

#include <stdlib.h>#include <iostream>#include <boost/format.hpp>using namespace std; int main( ) { cout << boost::format( "%2.3f, %d" ) % 1.23456 % 12 << endl; }

The bottom part is the boost: format-related program. First, use boost: format. We must first include "Boost/format. HPP "this example; after the example is included, you can use the boost: Format function.

While boost: format is the closest way to printf usage, that is, the above form (POSIX-printf style) after the cout is passed through, the results will be consistent

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

Exactly the same.

In practice, this example uses the format string "" % 2.3f, % d "to create a boost: Format object, this object is used for subsequent formatting. The formatted strings used here are exactly the same as those used for printf.

In addition to the POSIX-printf style above, some simple styles can also be used, the following is a simple example:

cout << boost::format( "%1%, %2%" ) % 1.23456 % 12 << endl;

In this lattice encoding method, it is in the formatted string, "% 1%" is used to represent the first change, and "% 2%" is used to represent the second change. Through this definition, we can adjust the sequence of the incremental data, or re-use a specific incremental data at the same time. For example:

cout << boost::format( "%1%, %2%, %1%" ) % 1.23456 % 12 << endl;

In this case, the final result will be "1.23456, 12, 1.23456 」. However, this method does not specify the formatting settings, so all changes will be exported using the formatting method.

 

Boost: Format object operations

As mentioned above, boost: format is actually a type. In actual use, a boost: Format object is generated, subsequent operations; all subsequent changes are sent to this object through Calling operator % in sequence.(Issue 2), And finally pass through operator <to export the information to cout.

As a result, printf itself is a variable-length argument function, so all the changes to be generated are, they are all written in the form of funny separation and writing data. These two seem similar in terms of programming methods, but they are completely different in terms of concepts and practices.

For example:

cout << boost::format( "%1%, %2%" ) % 1.23456 % 12 << endl;

In practice, it can be seen:

cout << ( ( boost::format( "%1%, %2%" ) % 1.23456 ) % 12 ) << endl;

The boost: Format operator is run in the form of objects. Therefore, the actual execution process is equivalent:

boost::format fmt( "%1%, %2%" );fmt % 1.23456;fmt % 12;cout << fmt << endl;

This also means that the developer can record the boost: Format object and use it again. For example, the following is a re-Example Using boost :: format object example:

boost::format fmt( "Test:< %1.2f, %1.2f >" );cout << ( fmt % 1.234 % 123.1 ) << endl;cout << fmt % 5.678 % 1 << endl;

However, operator % operator is used to change the boost: Format object (FMT) to the boost: Format object (FMT, therefore, the number of changes can be added in batches. However, if the number of changes does not match, the number of changes cannot appear in the initial segment, however, when the segment is reached, the program will still be replaced, so you must be careful when using it. However, after a snapshot is generated, you can re-import the new variable and re-upload the same boost: Format object.

 

Passed through boost: format to generate strings

The method mentioned above is to directly extract the result of Boost: format to ostream, what if we want to use the formatted result to generate a string called response? It is very simple, because boost already provides a corresponding function to do this. 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();

These two are basically the same, but the program programming method is different.

 

Legal disclaimer

I have mentioned POSIX printf style and simple style. In practice, the encoding method of the formatted string used by boost: format is based on unix98.

Open-group printf, and then make some extensions; its form is:

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

Most of the content is the same as the traditional printf, and only some are different.(Part 4)

For example, in the flags section, boost: format, except for the original "-", is directed to the left side, there are also new "=" for the center-to-end vertex and "_" for the internal-to-kernel (internal alignment). These two are not available in printf. In addition to using "%" to indicate the "%" character, you can also use "%"NT.
N spaces or '%' |NTX| "To fill in N x (x is a single dollar) functions.

In addition, some things are not exactly the same as printf, but some others will not be mentioned here; if you are interested, please take a test of differences of Behaviour vs printf on your own.

In actual use, it should be roughly divided into the following formats:

  1. % N %: (simple style) is the most simple and there is no formatting method. n is the first change.
  2. % Spec :( POSIX-printf style format string) This part is mainly compatible with the printf encoding method, which can basically be used directly by the encoding method used on printf. Of course, the spec part also supports the use of new things outside the boost: format definition Definition.
  3. % | Spec |: This is a representation separated by '|. Spec is basically the same as the former. The main character of this encoding method is that it can omit the character indicating the stereotypes ("type-conversion character" in printf 」), at the same time, you can also add the program availability.

    For example, "% |-5 |" indicates that the ratio to the left is 5, and the root type is different, and "%-5g", "%-5f", etc.

    It seems that the comparison method is more specific than others, maybe it is in the form of "% | 1 $ + 4.2 |". Its meaning is basically to set the first change (1 $ ), output is made in the form of "+ 4.2", and this parameter does not specify the output type. Therefore, in the response row, the type of the variable may be different.

 

Example

Due to the wide variety of Boost: Format applications, heresy does not intend to generate too many examples for Boost: format, basically, in the official release example, a group of heresy feels representative. below is the program release:

cout << boost::format("(x,y) = (%+5d,%+5d) ") % -23 % 35;cout << boost::format("(x,y) = (%|+5|,%|+5|) ") % -23 % 35;cout << boost::format("(x,y) = (%1$+5d,%2$+5d) ") % -23 % 35;cout << boost::format("(x,y) = (%|1$+5|,%|2$+5|) ") % -23 % 35;

The results of the four different boost: Format encoding methods are the same, and the result will be:

(x,y) = (  -23,  +35)

This group example also roughly represents boost: Format encoding in different forms. If there is something interesting about this group, let's take a look, we should be able to find the difference between these methods.

 

Performance questions

Boost: The format scheme is convenient to use, but in terms of performance, it is not very good, this point is put forward on the official website. Basically, in general, using printf will have the best performance, and iostream will be slower than printf, while boost: format is due to other overhead, so it will be slower. The official website also provides some metric data.
In release mode, iostream operations require a maximum of 1.6 times that of printf, while boost: format requires 2 ~ About 3 times, that is, about 3 ~ of printf ~ 5 times.

The boost: format is not efficient. Therefore, if the performance bottle operator of the program is output and processed in such strings, using boost: Format may not be a good choice, because it is indeed possible to make performance worse, in this case, the best method should still be back to use printf.

However, in practice, the main performance bottle category of a program should not be in this part. Therefore, if boost: format is used in this example, it should not significantly affect the overall performance. In contrast, boost :: the format and duration are less time-consuming. Therefore, in this case, boost: format should still be applicable.

 

Conclusion

For the introduction of Boost: format, this is probably the first section. In fact, the answer should not be complete. Many of the answer tokens have been skipped by heresy, but it is just a simple introduction. If you really want to have a complete meeting, you may have to go back to the official website. I believe that if you want to spend time, we should be able to find more advanced operations!

In addition, the boost: Format scheme is mainly extended based on the printf scheme method, therefore, heresy decided to skip a lot of relevant explanations in this article. But in fact, in the process of writing this article, the syntax of formatting strings in printf is also found, many of which were not noticed before by heresy and were not understood... Maybe, I want to study it again later...

 

Appendix
  1. Actually, it is a template class: basic_format.
  2. The boost: Format operator % definition method is actually similar to the ostream operator <, in the form of "format & format: Operator % (const
    T & X) ", a format test will be taken back, so you can keep using operator %.
  3. For the user's self-built model, the operator can be used on boost: foramt as long as it has a fixed operator <.
  4. The printf of Visual C ++ does not seem to support the positional format specification of formatted strings, but it should be usable on GCC.

Related Article

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.