I have a function with a parameter pack, I pass this pack to the fmt::format function, and I want to create a formatStr according to the args count, meaning add "{}#" for each passed argument.
I can do it using iterating, but is it possible to do this with one line solution? How to do it gracefully?
template <typename... Args>
void formatArgs( Args&&...args)
{
const auto size = sizeof...(Args);
std::string formatStr = ...// "{}#{}#{}..." - {}# should depend on args count
/*
std::ostringstream formatStr;
for (const auto& p : { args... })
formatStr << {}#";
*/
auto res = fmt::format(formatStr.c_str(), args...);
...
}
An ugly fold expression would work. It's only redeeming quality is that it's just one line, and in C++20 it should be a constexpr, so in C++20 this'll wind up to be a single std::string constructor call:
#include <string>
#include <iostream>
template<typename ...Args>
std::string string_from_args(Args && ...args)
{
return std::string{ ((args, std::string{"%s#"}) + ...) };
}
int main()
{
std::cout << string_from_args(1, 2, 3, 4) << "\n";
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With