以下节目:
#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>>在第一个空格处停止,lexical_cast检测到整个输入没有被消耗,并抛出一个异常。
有没有任何方法来教lexical_cast关于fbstring (或者更一般地说,任何string-like类型)?
发布于 2016-05-09 18:18:31
从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());
}https://stackoverflow.com/questions/37121743
复制相似问题