我已经看到了其他boost::lexical_cast
问题的一些答案,它们断言以下问题是可能的:
bool b = boost::lexical_cast< bool >("true");
这不适用于我的g++ 4.4.3 boost 1.43。(也许它在默认设置了std::boolalpha
的平台上工作是真的)
This是一个很好的字符串到布尔问题的解决方案,但是它缺少boost::lexical_cast提供的输入验证。
发布于 2010-12-18 04:21:42
我在这里发布了我自己的问题的答案,供其他可能正在寻找这样的东西的人使用:
struct LocaleBool {
bool data;
LocaleBool() {}
LocaleBool( bool data ) : data(data) {}
operator bool() const { return data; }
friend std::ostream & operator << ( std::ostream &out, LocaleBool b ) {
out << std::boolalpha << b.data;
return out;
}
friend std::istream & operator >> ( std::istream &in, LocaleBool &b ) {
in >> std::boolalpha >> b.data;
return in;
}
};
用法:
#include <boost/lexical_cast.hpp>
#include <iostream>
#include "LocaleBool.hpp"
int main() {
bool b = boost::lexical_cast< LocaleBool >("true");
std::cout << std::boolalpha << b << std::endl;
std::string txt = boost::lexical_cast< std::string >( LocaleBool( b ) );
std::cout << txt << std::endl;
return 0;
}
发布于 2013-07-18 03:43:15
除了答案形式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;
}
我个人喜欢这种方法,因为它隐藏了任何特殊的代码(例如,使用链接中的LocaleBool
或to_bool(...)
)来转换为bools。
发布于 2013-10-23 00:14:31
将您自己的模板放在boost lexical cast之上,以便进行解析。请注意示例中的"default“参数,以确保重载正常工作(如果需要,可以使用其他方法)。
template<typename T>
T Parse(const std::string& valStr, const T& default=T()) {
T result = boost::lexical_cast<T>(valStr);
}
然后,您可以专攻任何东西,包括bools:
template<>
bool Parse(const std::string& valStr, const bool& default=true) {
if(strcmp(valStr.c_str(), "true") == 0) {
return true;
}
return false;
}
显然,有许多方法可以做到这一点,你可以为true和false添加更多的条件(我会确保"TRUE“和"FALSE”的所有变体,比如"True",加上"T“和"F”都能正常工作)。您甚至可以将其扩展到数值解析。
https://stackoverflow.com/questions/4452136
复制相似问题