gpt4 book ai didi

c++ - std::to_string、boost::to_string 和 boost::lexical_cast 之间有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 21:55:34 26 4
gpt4 key购买 nike

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> 和它不会 throw 的表亲 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;
}

您可以选择这种形式来利用泛型函数中输入类型的更大灵 active ,或者生成 std::string从一个你知道不是基本数字类型的类型。


boost::to_string没有直接记录,似乎主要供内部使用。它的功能类似于 lexical_cast<std::string> ,而不是 std::to_string .

关于c++ - std::to_string、boost::to_string 和 boost::lexical_cast<std::string> 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com