c++ - 我如何使用 boost::lexical_cast 和 std::boolalpha?即 boost::lexical_cast< bool > ("true")

标签 c++ string boost lexical-cast

我看到了其他 boost::lexical_cast 问题的一些答案,断言以下是可能的:

bool b = boost::lexical_cast< bool >("true");

这不适用于 g++ 4.4.3 boost 1.43。 (也许它确实适用于默认设置 std::boolalpha 的平台)

This是字符串到 bool 问题的一个很好的解决方案,但它缺少 boost::lexical_cast 提供的输入验证。

最佳答案

除了答案表poindexter,你还可以包装来自here的方法在 boost::lexical_cast 的特殊版本中:

namespace boost {
    template<> 
    bool lexical_cast<bool, std::string>(const std::string& arg) {
        std::istringstream ss(arg);
        bool b;
        ss >> std::boolalpha >> b;
        return b;
    }

    template<>
    std::string lexical_cast<std::string, bool>(const bool& b) {
        std::ostringstream ss;
        ss << std::boolalpha << b;
        return ss.str();
    }
}

并使用它:

#include <iostream>
#include <boost/lexical_cast.hpp>

//... specializations

int main() {
    bool b = boost::lexical_cast<bool>(std::string("true"));
    std::cout << std::boolalpha << b << std::endl;
    std::string txt = boost::lexical_cast< std::string >(b);
    std::cout << txt << std::endl;

    return 0;
}

我个人喜欢这种方法,因为它隐藏了任何特殊代码(例如,使用链接中的 LocaleBoolto_bool(...))来转换为 bool 值或从 bool 值转换。

关于c++ - 我如何使用 boost::lexical_cast 和 std::boolalpha?即 boost::lexical_cast< bool > ("true"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357935/

相关文章:

c++ - 具有函数类型参数的模板导致编译器错误

c++ - 线程零文件描述符中的套接字

javascript - 仅包含特定单词的过滤数组

java - 我怎样才能让 Java 检查字符串是否匹配从末尾开始的模式?

c++ - 有没有办法在另一个#define 中执行#define?

C#/命令行界面 : Destructor not called if Dispose() used in it

java - 如何找到文本中复合词的出现

C++ 多字符串抓取器(正则表达式)

c++ - boost 线程 pthread_mutex_lock 问题

c++ - boost::counting_iterator range-v3 中的模拟