C++ 如何将boost::lexical\u cast与folly::fbstring一起使用?

C++ 如何将boost::lexical\u cast与folly::fbstring一起使用?,c++,boost,lexical-cast,folly,C++,Boost,Lexical Cast,Folly,以下节目: #include <boost/container/string.hpp> #include <boost/lexical_cast.hpp> #include <folly/FBString.h> #include <iostream> class foo { }; std::ostream& operator<<(std::ostream& stream, const foo&) { re

以下节目:

#include <boost/container/string.hpp>
#include <boost/lexical_cast.hpp>
#include <folly/FBString.h>
#include <iostream>

class foo { };

std::ostream& operator<<(std::ostream& stream, const foo&) {
  return stream << "hello world!\n";
}

int main() {
  std::cout << boost::lexical_cast<std::string>(foo{});
  std::cout << boost::lexical_cast<boost::container::string>(foo{});
  std::cout << boost::lexical_cast<folly::fbstring>(foo{});
  return 0;
}
这是因为
lexical\u cast
没有意识到
fbstring
是一种类似
string
的类型,只是做了通常的
stream>输出用于转换。但是
operator>
对于字符串,在第一个空格处停止,
lexical\u cast
检测到整个输入未被使用,并抛出异常


有没有什么方法可以教授
词法转换
关于
fbstring
(或者更一般地说,任何
类似字符串的类型)?

词法转换
文档来看,
std::string
显然是正常词法转换语义所允许的唯一类似字符串的异常,使强制转换的含义尽可能简单,并捕获尽可能多的转换错误。文档还指出,对于其他情况,可以使用替代方案,例如
std::stringstream

在您的情况下,我认为
to_fbstring
方法将是完美的:

template <typename T>
fbstring to_fbstring(const T& item)
{
    std::ostringstream os;

    os << item;

    return fbstring(os.str());
}
模板
fbstring到_fbstring(常数和项目)
{
std::ostringstream os;

操作系统是的,看起来你是对的。逻辑隐藏在
boost/lexical\u cast/detail/converter\u lexical\u streams.hpp
中,没有简单的自定义方法。我最终编写了自己的
lexical\u cast
包装器,委托给
boost::lexical\u cast
,专门用于
fbstring
template <typename T>
fbstring to_fbstring(const T& item)
{
    std::ostringstream os;

    os << item;

    return fbstring(os.str());
}