以下程序:
#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
类似的类型)?