std::to_string、boost::to_string和boost::lexical_cast<std::string>之间有何区别?

26
boost::to_string(位于boost/exception/to_string.hpp中)的目的是什么?它与boost::lexical_cast<std::string>std::to_string有何不同之处?

10
如果我记得历史没错的话,boost::to_string 先于 std::to_string 出现,这通常是情况如此。Boost 倾向于成为标准库接受之前的实验场。std::to_string 是 C++11 新增的。 - Cory Kramer
@Cyber:我建议你将这个写成一个(部分)答案。 - MikeMB
1
@CoryKramer,boost::to_string可能比较老,但它和std::to_string并不相同,而且std::to_string也不是基于它的(它们只是碰巧使用了相同的名称)。 - Jonathan Wakely
3个回答

35

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


11

还有一些区别:当将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版本更易读。


3
请不要只是粘贴代码,需要描述您的代码做了什么以及如何实现它。 - Paul Kertscher
2
这很简单,对于相同的双精度值,to_string() 和 lexical_cast() 的输出是一样的 ;-)) - Claus Klein
2
这些结果确实不同 - 这值得注意。但我不确定哪个结果更“正确”。 - Drew Dormann

-2

你提供的链接可能很有趣,但并未达到回答问题的水平。 - JarMan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接