Text Formatting For a Future Range-Based Standard Library

Speaker: Arno Schoedl

Audience level: Beginner | Intermediate | Advanced

category

Text formatting has been a favorite problem of C++ library authors for a long time. The standard C++ iostreams have been criticized for being difficult to use due to their statefulness and slow due to runtime polymorphism. Despite its age, printf is still popular because of simplicity and speed. The Boost library offers two more alternatives, Boost.Format and Boost.LexicalCast. And finally, the P0645 standard proposal sponsored by Facebook is currently finding its way through the C++ committee.

All these approaches are still firmly based on standard containers and iterators. But the Standard Library is changing radically with the advent of ranges, range adaptors and functional style programming in C++. Generating optimized code with metaprogramming is becoming standard fare.

In this talk, I want to convince you that the combination of ranges with a bit of metaprogramming makes for a very elegant solution to the text formatting problem. We introduce a form of ranges with internal iteration, which are generating their elements one by one rather than exposing external iterators. We can use these generator ranges to represent the values to be formatted, conceptually turning them into lazily evaluated strings. These can be used just like regular strings are used today: in function returns; as standard algorithm input; embedded into other, equally lazily evaluated strings; and so on, before they are finally expanded for display. By choosing the right interfaces, we can optimize this expansion at compile-time, making it no less pretty to write, but more efficient to expand than any text formatting approaches that rely on format strings that must be parsed at runtime.

I believe that this approach is the natural extension of a range-based future standard library to text formatting.