【问题标题】:How can I use boost::lexical_cast with folly::fbstring?如何将 boost::lexical_cast 与 folly::fbstring 一起使用?
【发布时间】: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 &lt;&lt; in; stream &gt;&gt; out; 进行转换。但是operator&gt;&gt; for strings 在第一个空格处停止,lexical_cast 检测到整个输入没有被消耗,并抛出异常。

有什么方法可以教lexical_cast 关于fbstring(或者,更一般地说,任何类似string 的类型)?

【问题讨论】:

    标签: c++ boost lexical-cast folly


    【解决方案1】:

    通过查看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());
    }
    

    【讨论】:

    • 是的,看起来你是对的。逻辑隐藏在boost/lexical_cast/detail/converter_lexical_streams.hpp 中,没有简单的方法来定制它。我最终编写了自己的 lexical_cast 包装器,它委托给 boost::lexical_cast,并专门针对 fbstring
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2021-05-06
    相关资源
    最近更新 更多