std :: to_string,boost :: to_string和boost :: lexical_cast< std :: string>之间有什么区别? [英] What's the difference between std::to_string, boost::to_string, and boost::lexical_cast<std::string>?
问题描述
boost::to_string
(在boost/exception/to_string.hpp
中找到)的用途是什么,它与boost::lexical_cast<std::string>
和std::to_string
有何区别?
What's the purpose of boost::to_string
(found in boost/exception/to_string.hpp
) and how does it differ from boost::lexical_cast<std::string>
and std::to_string
?
推荐答案
std::to_string
(自C ++ 11起可用)专门用于基本数字类型.它还具有 std::to_wstring
变体.
std::to_string
, available since C++11, works on fundamental numeric types specifically. It also has a std::to_wstring
variant.
它旨在产生与 sprintf
会.
It is designed to produce the same results that sprintf
would.
您可以选择此表单,以避免依赖于外部库/标题.
You may choose this form to avoid dependencies on external libraries/headers.
失败引发函数 boost::lexical_cast<std::string>
及其非投掷表亲
The throw-on-failure function boost::lexical_cast<std::string>
and its non-throwing cousin boost::conversion::try_lexical_convert
work on any type that can be inserted into a std::ostream
, including types from other libraries or your own code.
针对常见类型存在优化的专业化,其通用形式类似于:
Optimized specializations exist for common types, with the generic form resembling:
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
.
You may choose this form to leverage greater flexibility of input types in generic functions, or to produce a std::string
from a type that you know isn't a fundamental numeric type.
boost::to_string
没有直接记录,似乎主要供内部使用.其功能类似于lexical_cast<std::string>
,而不是std::to_string
.
boost::to_string
isn't directly documented, and seems to be for internal use primarily. Its functionality behaves like lexical_cast<std::string>
, not std::to_string
.
这篇关于std :: to_string,boost :: to_string和boost :: lexical_cast< std :: string>之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!