I've seen some answers to other boost::lexical_cast
questions that assert the following is possible:
bool b = boost::lexical_cast< bool >("true");
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)
This is a nice solution to the string to bool problem but it lacks input validation that boost::lexical_cast provides.
Put together your own template on top of boost lexical cast for parsing. Note the "default" parameter in the example to ensure overloading works correctly (feel free to use another means if you want).
Then, you can specialize for ANYTHING, including bools:
Obviously there are a number of ways to do this, and you can add more conditions for true vs false (I'd make sure all variants of "TRUE" and "FALSE" like "True", plus "T" and "F" work right). You could even extend it to numeric parsing.
I'm posting the answer to my own question here for others who may be looking for something like this:
usage:
In addition to the answer form poindexter, you can wrap the method from here in a specialized version of
boost::lexical_cast
:And use it:
I personally liked this approach because it hides any special code (e.g. using
LocaleBool
orto_bool(...)
from the link) for converting to/from bools.