问题描述
我已经看到了一些答案,其他的boost :: lexical_cast的是断言,以下是可能的
问题:
I've seen some answers to other boost::lexical_cast
questions that assert the following is possible:
bool b = boost::lexical_cast< bool >("true");
这不适合我使用g ++ 4.4.3提升1.43工作。 (也许这是真的,它的工作原理,其中的std :: boolalpha是默认设置的平台上)
This doesn't work for me with g++ 4.4.3 boost 1.43. (Maybe it's true that it works on a platform where std::boolalpha is set by default)
是一个很好的解决方案,以字符串为bool的问题,但它缺乏输入验证了提高:: lexical_cast的提供。
This is a nice solution to the string to bool problem but it lacks input validation that boost::lexical_cast provides.
推荐答案
我张贴的答案在这里我自己的问题为别人谁可能是在寻找这样的事情:
I'm posting the answer to my own question here for others who may be looking for something like this:
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;
}
这篇关于我该如何使用boost :: lexical_cast的和std :: boolalpha?即提高:: lexical_cast的&LT;布尔&GT;(QUOT;真&QUOT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!