以下程序:
#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;
}
给出这个输出:
hello world!
hello world!
terminate called after throwing an instance of 'boost::bad_lexical_cast'
what(): bad lexical cast: source type value could not be interpreted as target
这是因为 lexical_cast
没有意识到 fbstring
是 string
-like 类型,简单地做它通常的 stream << in; stream >> out;
为转换。但是operator>>
for strings 在第一个空格处停止,lexical_cast
检测到整个输入未被消耗,并抛出异常。
有没有什么方法教lexical_cast
关于fbstring
(或者,更一般地说,任何类似 string
的类型)?
最佳答案
从查看 lexical_cast
文档可以看出,std::string
显然是唯一允许正常词法转换语义的类似字符串的异常,以保持其含义尽可能直接地进行转换,并尽可能多地捕获可能的转换错误。该文档还说,对于其他情况,可以使用替代方案,例如 std::stringstream
。
在你的情况下,我认为 to_fbstring
方法是完美的:
template <typename T>
fbstring to_fbstring(const T& item)
{
std::ostringstream os;
os << item;
return fbstring(os.str());
}
关于c++ - 如何将 boost::lexical_cast 与 folly::fbstring 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37121743/