gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:59:32 25 4
gpt4 key购买 nike

我看到了其他 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com