除了问答形式波因德克斯特您可以将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。
关于发布自己的问题答案的意见是混合的,但至少应将答案发布为答案。 – robert 2010-12-15 16:16:54
请发表您的答案**作为答案**。 – 2010-12-15 16:17:19
编辑! (出于某种原因,我没有通过电子邮件发送您的评论。) – poindexter 2010-12-17 20:24:36