A string formatting library in 65 lines of C++
14 points by riki
14 points by riki
Very nice, this is pretty much exactly what I planned to build for an embedded project, so thar saved me a bunch of time!
The only “issue” is that for localization you actually need to index the placeholders, since different languages have different word order. I ran into this with printf, which is decidedly not localization-friendly. The solution I came up with was to check if the format specifies appear in the exact same order, but it’s not ideal. I think Qt’s solution with QString("point: %1, %2")
is actually pretty good!
For an embedded project, I wrote a small formatting library that takes an array of unitptr_t values with type descriptors, with template wrappers that do the type erasure and call the function. The call-site code is similar to printf but the API is type safe. It doesn’t do positional arguments (or format specifiers) but it would be quite easy to extend it to do so. It can also handle custom formatting, so I can print things like IP addresses and MAC addresses with it. It’s based on the little formatter I wrote for snmalloc so it could print nice error messages even if libc was likely to be broken.
Yeah, I didn’t think of that much honestly… I don’t think my video game strings are gonna be complex enough to warrant that, but it would be a headache with this kind of system (parsing driven by a fold expression.)
Perhaps then would be the time to introduce an intermediary buffer for the format arguments, such that they can be indexed freely; but I’ve decided not to think about it too much, at least not until localisation requirements demand it.