I have some code like this:
const std::string first = "|>first {} thing<|";
const std::string second = "|>second thing<|";
const std::string third = "|>third thing<|";
const std::string fourth = "|>fourth thing<|";
const std::string out = std::format("Testing {} format {} string {}", first, second, third, fourth);
std::cout << out << std::endl;
This code outputs the following:
Testing |>first {} thing<| format |>second thing<| string |>third thing<|
I would like the code to output:
Testing |>first |>second thing<| thing<| format |>third thing<| string |>fourth thing<|
The difference is the |>first {} thing<|
has been replaced by |>first |>second thing<| thing<|
. That is, the format is applied recursively. std::format
has a lot of compile time checks, but in theory nothing is stopping std::vformat
from being able to be applied recursively.
Before I implement this functionality on my own, I would like to know whether it exists in the standard library, or if another robust solution is already available.
Real world example:
I have five (about 40 really) different queries all which need data1, data2, data3, ...
just in a different location. The data will be known at runtime, but the position will be known at compile time. I have the option of five different query classes, or one templated with different specializations: using Query1 = BasicQuery("BLAH {} BLAH");
using Query2 = BasicQuery("BLAH BLAH {}");
so on. This can be the difference in both 1500 lines of code vs ~250 and a nicer calling interface vs a convoluted one (single execute function per class, vs a function per query if I chose to just have one class with all the queries).
Additionally, adding a function per query is not a choice. Each query has a different return type (and indeed different number of returns) based on the nature of the query. The class also handles parsing the returned data based on the return type and number of returns. Template specializations are a really nice solution to this. I am hoping I can also use the specializations for the query string itself.
Is there a "recursive" std::format?
No, there is not. You would have to write one yourself.
I have the option of five different query classes, or one templated
Consider using a templating engine.
My 1 min search for https://www.google.com/search?q=C%2B%2B+templating+engine resulted in Is there a good template engine for C++ , https://jinja2cpp.github.io/ and https://github.com/pantor/inja .