我通过谷歌找到了下面的代码。它几乎完成了我想要它做的事情,除了它没有提供一种方法来指示精度,就像 '%.*f' 在 C 类型格式字符串中所做的那样。此外,它不提供任何超过小数点后 5 位的内容。我将不得不坚持使用 C 字符串和 snprintf 吗?
#include <string>
#include <sstream>
#include <iostream>
template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
std::ostringstream oss;
oss << f << t;
return oss.str();
}
int main()
{
std::cout<<to_string<double>(3.1415926535897931, std::dec)<<std::endl;
return 0;
}