I was concatenating a lot of strings lately, usually the results of std::format:
std::string str;
str += std::format("the answer is {}\n", 42);
str += std::format("what is the {}?\n", "question");
I got tired of temporary strings and switched to std::format_to:
std::string str;
std::format_to(std::back_inserter(str), "the answer is {}\n", 42);
std::format_to(std::back_inserter(str), "what is the {}?\n", "question");
But now it was horribly verbose, so I figured I created a helper:
auto make_append_format(std::string& str)
{
return [&str]<class... TArgs>(const std::format_string<TArgs...> fmt, TArgs&&... args)
{ return std::vformat_to(std::back_inserter(str), fmt.get(), std::make_format_args(args...)); };
}
And now the code looks a bit neater:
std::string str;
const auto append_format = make_append_format(str);
append_format("the answer is {}\n", 42);
append_format("what is the {}?\n", "question");
Any input on style and potential issues with make_append_format? Should I forward the parameter pack?
make_append_formatto take a second parameter for the inserter, defaulting tostd::back_inserter, in case you want to use it with other insertion iterators later. It would look something like this:template<typename Func=decltype(std::back_inserter<std::string>)> auto make_append_format(std::string& str, Func f = std::back_inserter). It's not necessary or anything, though, and there isn't really a cleaner way to do it sinceautoparameters don't play nicely with default arguments; it'd just make it a bit more reusable if you ever run into the same situation again. \$\endgroup\$