我已经看到其他boost::lexical_cast
个问题的一些答案,断言以下是可能的:
bool b = boost::lexical_cast< bool >("true");
这对g ++ 4.4.3 boost 1.43不起作用。 (也许它确实适用于默认设置std :: boolalpha的平台)
This是解决字符串bool问题的一个很好的解决方案,但它缺少boost :: lexical_cast提供的输入验证。
答案 0 :(得分:16)
我在这里发布了我自己的问题的答案,其他人可能正在寻找这样的事情:
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;
}
答案 1 :(得分:14)
除了答案形式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或来自bools。
答案 2 :(得分:0)
将自己的模板放在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”正常工作)。您甚至可以将其扩展为数值解析。