Boost.Format provides a class called boost::format, wich is defined in boost/format.hpp Similar to std::printf(), a string containing special characters to control formatting is passed to the constructor of boost::format. The data that replaces these special characters in the output is linked via the operator operator%
#include <boost/format.hpp> #include <iostream> int main() { std::cout << boost::format(%1%.%2%.%3%) % 12 % 5 % 2014 << std::endl;
std::cout << boost::format(%2%/%1%/%3%) % 12 % 5 % 2014 << std::endl; return 0; }
The boost format string uses numbers placed between two percent signs as placeholders for the actual data, which will be linked in using operator%.
输出为:
12.5.2014
5/12/2014
Boost.Format is boty type safe and extensible. Objects of any type can be used with Boost.Format as long as the operator operator<< is overloaded for std::ostream.
#include <boost/format.hpp> #include <string> #include <iostream> struct animal { std::string name; int legs; }; std::ostream& operator<<(std::ostream& os, const animal& a) { return os << a.name << "," << a.legs; } int main() { animal a{"cat", 4}; std::cout << boost::format("%1%") %a << std::endl; return 0; }
输出为:cat,4
uses boost::format to write an object of the user-defined type animal to standard output. This is possible because the stream operator is overloaded for animal.