首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何使用boost::lexical_cast与愚蠢::fbstring?

我如何使用boost::lexical_cast与愚蠢::fbstring?
EN

Stack Overflow用户
提问于 2016-05-09 17:18:29
回答 1查看 332关注 0票数 2

以下节目:

代码语言:javascript
复制
#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;
}

给出这个输出:

代码语言:javascript
复制
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类型)?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-09 18:18:31

lexical_cast文档来看,std::string显然是唯一允许正常词法转换语义的类似字符串的异常,以保持强制转换的含义尽可能简单,并尽可能捕获尽可能多的可能的转换错误。文档还指出,对于其他情况,可以使用替代方案,如std::stringstream

在您的例子中,我认为to_fbstring方法将是完美的:

代码语言:javascript
复制
template <typename T>
fbstring to_fbstring(const T& item)
{
    std::ostringstream os;

    os << item;

    return fbstring(os.str());
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37121743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档