I\'ve seen some answers to other boost::lexical_cast
questions that assert the following is possible:
bool b = boost::lexical_cast< bool >
In addition to the answer form poindexter, you can wrap the method from here in a specialized version of boost::lexical_cast
:
namespace boost {
template<>
bool lexical_cast(const std::string& arg) {
std::istringstream ss(arg);
bool b;
ss >> std::boolalpha >> b;
return b;
}
template<>
std::string lexical_cast(const bool& b) {
std::ostringstream ss;
ss << std::boolalpha << b;
return ss.str();
}
}
And use it:
#include
#include
//... specializations
int main() {
bool b = boost::lexical_cast(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;
}
I personally liked this approach because it hides any special code (e.g. using LocaleBool
or to_bool(...)
from the link) for converting to/from bools.