c++ - 如何将 boost::lexical_cast 与 folly::fbstring 一起使用?

标签 c++ boost lexical-cast folly

以下程序:

#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没有意识到 fbstringstring -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/

相关文章:

c++ - boost::lexical_cast int 到用零填充的字符串

c++ - 是否有任何 IID_XXX 可以从 Internet Explorer 获取焦点选项卡?

android - Android 上的 Boost.Asio 因找不到服务而失败(Boost 1.53;NDK r8e)

c++ - boost 定时器使用问题

c++ - boost::asio::async_read 不断在命名管道上返回 eof

c++ - 我应该什么时候使用 Boost 的 lexical_cast?它是不得已的机制吗?

c++ - '../controlpanel.ui' 需要 Qt : No rule to make target 'ui_controlpanel.h' ,。停止

c++ - 将 typedef 映射插入哈希表

c++ - 花栗鼠:将多边形分解成小块