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());
}