简单总结一下void.pointer的解决方案以及Praetorian、TC和Jarod42提出的提示,我提供最终版本(在线demo)
#include <boost/format.hpp>
#include <iostream>
template<typename... Arguments>
std::string FormatArgs(const std::string& fmt, const Arguments&... args)
{
boost::format f(fmt);
std::initializer_list<char> {(static_cast<void>(
f % args
), char{}) ...};
return boost::str(f);
}
int main()
{
std::cout << FormatArgs("no args\n"); // "no args"
std::cout << FormatArgs("%s; %s; %s;\n", 123, 4.3, "foo"); // 123; 4.3; foo;
std::cout << FormatArgs("%2% %1% %2%\n", 1, 12); // 12 1 12
}
此外,正如 TC 所指出的,使用从 C++17 开始可用的折叠表达式语法,可以以更简洁的方式重写 FormatArgs 函数
template<typename... Arguments>
std::string FormatArgs(const std::string& fmt, const Arguments&... args)
{
return boost::str((boost::format(fmt) % ... % args));
}