【发布时间】:2016-09-04 10:34:57
【问题描述】:
以下程序:
#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 的类型,而只是按照通常的stream << in; stream >> out; 进行转换。但是operator>> for strings 在第一个空格处停止,lexical_cast 检测到整个输入没有被消耗,并抛出异常。
有什么方法可以教lexical_cast 关于fbstring(或者,更一般地说,任何类似string 的类型)?
【问题讨论】:
标签: c++ boost lexical-cast folly