Formatting

The Xavax C++ Library (libCx) provides a facility for formatting text in a type-safe manner. The Formatter class formats text and parameters under control of a format string in a manner similar to the printf function in the stdio library. CStringFormatter, StreamFormatter, and StringFormatter are derived from Formatter and direct the output characters to a character array (C String), a stream, or a String object.

To maintain type safety, each parameter is converted to a Variant before it is passed to the print method. From the client's perspective, this conversion happens automatically since the print method only accepts Variants as parameters. Variant provides constructors accepting all supported types which are used by the compiler to do type conversion. The client uses a formatter as follows.
int i = 123;
double d = 123.456;
char *s = "test string";
char *format = "i = %d\nd = %f\ns = %s\n";
StreamFormatter formatter = new StreamFormatter(cout);
formatter.print(format, i, d, s);

The compiler converts the last statement to the equivalent of this statement.
formatter.print(format, Variant(i), Variant(d), Variant(s));

The print method is overloaded to accept between 1 and 20 parameters. This gives the illusion that the print method signature accepts a format parameter and a variable number of Variant parameters.

To improve efficiency, a format string can be compiled in advance using the Format class. A Format is created once and passed to the print method of any Formatter class as the first parameter instead of a format string. When employed within loops or other frequently executed code, this is significantly more efficient than parsing the format string each time the print method is called.

404-382-9128 XAVAX info@xavax.com