boost::to_string
(位于boost/exception/to_string.hpp
中)的目的是什么?它与boost::lexical_cast<std::string>
和std::to_string
有何不同之处?boost::to_string
(位于boost/exception/to_string.hpp
中)的目的是什么?它与boost::lexical_cast<std::string>
和std::to_string
有何不同之处?std::to_string
自C++11起可用,专门适用于基本数值类型。它也有一个std::to_wstring
变体。
它的设计目的是生成与sprintf
相同的结果。
您可以选择这种形式以避免对外部库/头文件的依赖。
抛出异常的函数boost::lexical_cast<std::string>
及其不会抛出异常的变体boost::conversion::try_lexical_convert
适用于任何可以插入到std::ostream
中的类型,包括来自其他库或您自己代码的类型。
针对常见类型存在优化的特殊处理,通用格式如下:
template< typename OutType, typename InType >
OutType lexical_cast( const InType & input )
{
// Insert parameter to an iostream
std::stringstream temp_stream;
temp_stream << input;
// Extract output type from the same iostream
OutType output;
temp_stream >> output;
return output;
}
你可以选择这种形式来利用通用函数中更灵活的输入类型,或者从你知道不是基本数字类型的类型生成std::string
。
boost::to_string
没有直接的文档,并且似乎主要用于内部使用。它的功能类似于lexical_cast<std::string>
,而不是std::to_string
。
还有一些区别:当将double转换为字符串时,boost::lexical_cast的工作方式会有所不同。 请考虑以下代码:
#include <limits>
#include <iostream>
#include "boost/lexical_cast.hpp"
int main()
{
double maxDouble = std::numeric_limits<double>::max();
std::string str(std::to_string(maxDouble));
std::cout << "std::to_string(" << maxDouble << ") == " << str << std::endl;
std::cout << "boost::lexical_cast<std::string>(" << maxDouble << ") == "
<< boost::lexical_cast<std::string>(maxDouble) << std::endl;
return 0;
}
结果
$ ./to_string
std::to_string(1.79769e+308) == 179769313486231570814527423731704356798070600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
boost::lexical_cast<std::string>(1.79769e+308) == 1.7976931348623157e+308
如您所见,boost版本使用指数表示法(1.7976931348623157e+308),而std::to_string则打印每个数字和六个小数位。对于您的目的,其中一个可能比另一个更有用。我个人认为boost版本更易读。
这里有一个整数转字符串的基准测试,希望它对浮点数和双精度浮点数的转换也适用 C++中快速整数转字符串基准测试。
boost::to_string
先于std::to_string
出现,这通常是情况如此。Boost 倾向于成为标准库接受之前的实验场。std::to_string
是 C++11 新增的。 - Cory Kramerboost::to_string
可能比较老,但它和std::to_string
并不相同,而且std::to_string
也不是基于它的(它们只是碰巧使用了相同的名称)。 - Jonathan Wakely