标准库函数将提供operator <<的对象转换为std :: string

Flo*_*ers 3 c++ iostream stdstring ostream c++11

我刚刚注意到我在我的C++ 11应用程序中使用了以下代码(它运行得很安静):

template <typename T>
std::string output_streamable_to_string(T const& kObject) {
  std::ostringstream os;
  os << kObject;

  return os.str();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:标准库(std)中是否存在提供此功能的函数?

我知道std::to_string存在,但只适用于标准库数据类型.我想将a转换boost::asio::ip::udp::endpoint为a std::string.既然boost::asio::ip::udp::endpoint只提供了一个operator<<函数,我需要将其转换std::ostream为a std::string.

For*_*veR 5

不,标准C++中没有这样的功能.但是既然你使用了boost - 你可以使用boost :: lexical_cast,或者只使用你自己的.