使用 boost::lexical_cast 将 UUID 转换为字符串时出现 Boost 编译错误

Boost compile error on converting UUID to string using boost::lexical_cast

我有这段代码,它基于 SO 中的几篇文章:

boost::uuids::uuid uuid = boost::uuids::random_generator()();
auto uuidString= boost::lexical_cast<std::string>(uuid);

但是当我编译这段代码时,出现了这个错误:

Source type is neither std::ostream`able nor std::wostream`able     C:\Local\boost\boost\lexical_cast\detail\converter_lexical.hpp  

如何解决这个错误?

你可以试试:

std::stringstream ss;
std::string       uuidStr;

boost::uuids::uuid uuid = boost::uuids::random_generator()();

ss << uuid;
ss >> uuidStr;

Documentation 状态:

Stream Operators

The standard input and output stream operators << and >> are provided by including boost/uuid/uuid_io.hpp. The string representation of a uuid is hhhhhhhh-hhhh-hhhh-hhhh-hhhhhhhhhhhh where h is a hexidecimal digit.

boost::uuids::uuid u1; // initialize uuid

std::stringstream ss;
ss << u1;

boost::uuids::uuid u2;
ss >> u2;

assert(u1, u2);

但是 lexical_cast 应该也能正常工作。

也许您应该检查 uuid 实际包含的内容,以确定生成的 uuid.

是否有问题

还有:

boost::uuids::uuid u; // initialize uuid

std::string s1 = to_string(u);

根据文档,应该稍微快一些。

你错过了包含,我猜:

Live On Coliru

#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>

int main() {
    boost::uuids::uuid uuid = boost::uuids::random_generator()();
    auto uuidString = boost::lexical_cast<std::string>(uuid);
}