【问题标题】:Standard Library function to convert an object providing operator<< to a std::string将提供 operator<< 的对象转换为 std::string 的标准库函数
【发布时间】:2015-04-17 09:21:00
【问题描述】:

我刚刚注意到我在我的 C++11 应用程序中使用了以下代码(运行良好):

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

  return os.str();
}

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

我知道std::to_string 存在,但它只适用于标准库数据类型。我想将boost::asio::ip::udp::endpoint 转换为std::string。由于boost::asio::ip::udp::endpoint 只提供operator&lt;&lt; 函数,我确实需要将std::ostream 转换为std::string

【问题讨论】:

  • 恐怕这已经是标准库的方法了:-)
  • 你想要的叫做序列化。查看protobufmsgpack 或类似picojson serializer
  • @Dmitry Ledentsov:使用序列化库/框架完全矫枉过正。我只想将一个简单的数据类型或对象转换为std::string。 @ForEveR 回答了这个问题。我知道你提到的前两个库。
  • 我感觉to_string 可能像swap 一样适合ADL 使用,遗憾的是boost 并没有真正为它提供to_string 实现。
  • @FlorianWolters 当然,这取决于你想要什么。 T未在问题范围内定义

标签: c++ c++11 iostream stdstring ostream


【解决方案1】:

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

【讨论】:

  • 真的很难过。 :D 但是由于我已经在我当前的项目中使用了 Boost.Asio,我将使用boost::lexical_cast(已经忘记了)。对于不需要 Boost 的项目,我将在原始帖子中保留该功能。
  • boost 的 lexical_cast 无论如何都是一个只有头文件的库,所以如果你只是将它包含到一个不“使用 boost”的项目中并不重要,因为不会有任何外部依赖项。并且由于它是模板化的,因此尺寸增加应该很小
猜你喜欢
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多