【发布时间】: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<< 函数,我确实需要将std::ostream 转换为std::string。
【问题讨论】:
-
恐怕这已经是标准库的方法了:-)
-
你想要的叫做序列化。查看protobuf、msgpack 或类似picojson serializer
-
@Dmitry Ledentsov:使用序列化库/框架完全矫枉过正。我只想将一个简单的数据类型或对象转换为
std::string。 @ForEveR 回答了这个问题。我知道你提到的前两个库。 -
我感觉
to_string可能像swap一样适合ADL 使用,遗憾的是boost 并没有真正为它提供to_string实现。 -
@FlorianWolters 当然,这取决于你想要什么。
T未在问题范围内定义
标签: c++ c++11 iostream stdstring ostream