本实例基于C++11的可变长参数实现:
#include
#include
#include
static void _format_help(
std::ostringstream& os, const std::string& format, std::size_t offset)
{
os << format.substr(offset, format.size() - offset);
}
template
static void _format_help(
std::ostringstream& os, const std::string& format, std::size_t offset, T arg, Args...args)
{
std::size_t off = format.find("{}", offset);
if (off == std::string::npos) {
os << format.substr(offset, format.size() - offset);
return;
}
os << format.substr(offset, off - offset) << arg;
_format_help(os, format, off + 2, args...);
}
/*
格式化输出成字符串,需要格式化的地方使用{}即可
如:
format("this is {}, age: {}, height: {}m", "Alice", 18, 1.72);
输出:"this is Alice, age: 18, height: 1.72m"
format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72);
输出:"this is Alice, age: 18, height: 1.72m {}m"
format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72, 555, 666);
输出:"this is Alice, age: 18, height: 1.72m 555m"
*/
template
std::string format(const std::string& format, Args... args)
{
std::ostringstream os;
_format_help(os, format, 0, args...);
return std::move(os.str());
}
int main(int argc, char* argv[])
{
std::cout << format("one {} two {} three {} {} {} {}", 1, 2, 3, 4.5, "123", "this is my test") << std::endl;
std::cout << format("this is {}, age: {}, height: {}m", "Alice", 18, 1.72) << std::endl;
std::cout << format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72) << std::endl;
std::cout << format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72, 555, 666) << std::endl;
return 0;
}
/*
one 1 two 2 three 3 4.5 123 this is my test
this is Alice, age: 18, height: 1.72m
this is Alice, age: 18, height: 1.72m {}m
this is Alice, age: 18, height: 1.72m 555m
*/
若编译器支持C++20,则可以直接使用