I'm writing a lightweight parsing library for embedded systems and try to avoid iostream. What I want to do is write variables to a buffer like vsnprintf() but I don't want to specify the format string, much rather the format string should be infered from the arguments passed to my variadic template wrapper. Here's an example:
#include <cstddef>
#include <string>
#include <cstdio>
template <typename... Ts>
void cpp_vsnprintf(char* s, size_t n, Ts&&... arg)
{
std::vsnprintf(s, n, /*how to deduce format string?*/, arg...);
}
int main()
{
char buf[100];
cpp_vsnprintf(buf, 100, "hello", 3, '2', 2.4);
printf(buf);
}
I'm looking for a performant solution, maybe the format string could be composed at compile time? Or is there maybe an stl function that does exactly what I'm asking for?
I figured it out with some inspiration from this thread
Demo
Output:
You can see that format strings are neatly packed into the binary: